我使用httpie来测试我的自定义验证Django的(使用TokenAuthentication):“non_field_errors”:“无法使用提供的凭据登录
http POST http://127.0.0.1:8000/api-token-auth/ username='username1' password='Password123'
我确实创造了使用AbstractUser
一个自定义的身份验证的对象。
使用TokenAuthentication,我跟着文档,然后在我的REST_FRAMEWORK
设置添加我的自定义TokenAuthentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'regis.models.CustomAuthentication',
)
}
并在我安装的应用程序中添加了rest_framework.authtoken
。
我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设置添加rest_framework.authentication.TokenAuthentication
。我仍然使用自定义身份验证来提取我的用户。
它看起来像这样(不打算格式化从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/
只是为了回答您的好奇心:不,如果您使用的是自定义用户,则不需要自定义身份验证。我在工作中使用的构建具有自定义用户,并使用Django附带的默认ModelBackend。 :) – Neelik
@Neelik ayyyee勾搭我在那里的工作! –
也许当公司增长一点时:P我们现在仍然是一个小本地团体。 – Neelik