gpt4 book ai didi

Django(使用TokenAuthentication): "non_field_errors": "Unable to log in with provided credentials?

转载 作者:行者123 更新时间:2023-12-02 04:39:01 25 4
gpt4 key购买 nike

我正在使用 httpie 来测试我的自定义身份验证。

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)

url.py:

urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token),

]

我非常关注 DRF 文档 ( http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication )。如果需要任何其他信息来解决此问题,请告诉我,我会更新。对我所缺少的任何帮助都会很棒。

补充:出于好奇,如果我有自定义用户,我是否需要创建自定义身份验证系统?

更新:

我刚刚删除了上面的类,并在我的 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/

最佳答案

如果您在 DRF 代码中搜索错误字符串,您会发现以下内容(在 authtoken/serializers.py 中:

from django.contrib.auth import authenticate
...

if username and password:
user = authenticate(username=username, password=password)

if user:
# From Django 1.10 onwards the `authenticate` call simply
# returns `None` for is_active=False users.
# (Assuming the default `ModelBackend` authentication backend.)
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
...

所以看起来,根据您使用的 Django 版本,这些凭据不正确,或者用户不活跃(对于 Django >= 1.10)?

您是否尝试过使用这些凭据手动登录管理员来验证它们?

关于Django(使用TokenAuthentication): "non_field_errors": "Unable to log in with provided credentials?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42429477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com