我正在使用 httpie 来测试我的自定义身份验证。
http POST http://127.0.0.1:8000/api-token-auth/ username='username1' password='Password123'
我确实使用创建了一个自定义身份验证对象AbstractUser
.
使用 TokenAuthentication,我按照文档操作并在我的REST_FRAMEWORK
设置:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'regis.models.CustomAuthentication',
)
}
并添加了rest_framework.authtoken
在我安装的应用程序中。
My AUTHENTICATION_BACKEND
如下:
AUTHENTICATION_BACKENDS = [ 'regis.models.CustomAuthentication' ]
这是我的自定义身份验证类:
class CustomAuthentication(authentication.TokenAuthentication):
def authenticate(self, request):
username = request.META.get('X_USERNAME')
print(username)
user_model = get_user_model()
if not username:
return None
try:
user = user_model.objects.get(username=username)
except User.DoesNotExist:
raise exceptions.AuthenticationFailed('No such user')
return (user, None)
urls.py:
urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token),
]
我非常关注 DRF 文档(http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication)。如果需要任何其他信息来解决此问题,请告诉我,我会更新。对我所缺少的任何帮助都会很棒。
添加:出于好奇,如果我有自定义用户,我是否需要制作自定义身份验证系统?
UPDATE:
我刚刚删除了上面的类,并添加了rest_framework.authentication.TokenAuthentication
在我的 REST_FRAMEWORK 设置中。我仍在使用自定义身份验证来获取我的用户。
它看起来像这样(不打算格式化它。从 VIM 格式化代码太糟糕了):
class CustomAuthentication(object):
def authenticate(self, email=None, password=None):
User = get_user_model()
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return None
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user_model = get_user_model()
user = user_model.objects.get(pk=user_id)
except User.DoesNotExist:
return None
我使用这个 Django 文档来创建该代码:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/