【问题标题】:Create a custom authentication创建自定义身份验证
【发布时间】:2026-01-28 17:35:01
【问题描述】:

我正在将数据库转移到一个新项目,更准确地说是用户。 不要问我为什么,但是旧数据库中的密码先用 md5 哈希,然后用 sha256 哈希。

我正在使用 django-rest-auth 来管理登录。

url(r'^api/rest-auth/', include('rest_auth.urls')),

我添加了自定义身份验证方法:

REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (
     'users.auth.OldCustomAuthentication',
     'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
  )
}

这是我的授权文件:

class OldCustomAuthentication(BaseAuthentication):
    def authenticate(self, request):
        try:
            password = request.POST['password']
            email = request.POST['email']
        except MultiValueDictKeyError:
            return None

        if not password or not email:
            return None

        password = hashlib.md5(password.encode())
        password = hashlib.sha256(password.hexdigest().encode())

        try:
            user = User.objects.get(email=email, password=password.hexdigest())
        except User.DoesNotExist:
            return None

        # User is found every time
        print('FOUND USER', user)
        return user, None

但是当我请求http://apiUrl/rest-auth/login/时我仍然收到错误:

{
    "non_field_errors": [
        "Unable to log in with provided credentials."
    ]
}

你有什么想法吗?或者我做错了。

提前谢谢你。

杰里米。

【问题讨论】:

  • 我很确定在散列时使用了盐。这是文档:docs.djangoproject.com/en/2.1/topics/auth/passwords 所以它不仅仅是密码的哈希值。
  • 您的返回行是否需要是一个元组而不是两个变量?参考文档(见代码示例):django-rest-framework.org/api-guide/authentication/#example
  • 问题是我在我的新数据库中找到了我的用户。我只想知道我需要返回什么才能说“嘿,你已连接”。我认为返回 user, None 会让 django-rest-framework 知道该用户使用了良好的凭据。和@MrName,不管有没有括号,都是一样的
  • 已经尝试删除 JSONWebTokenAuthentication 看看它是否可以这样工作?
  • 是的,我仍然收到来自端点的相同响应 /rest-auth/login/ ...您可以在此处查看调试器的屏幕截图:imgur.com/a/uhzqM2a

标签: python django python-3.x django-rest-framework django-rest-auth


【解决方案1】:

按照@MrName 的建议,我设法解决了我的问题。

所以我在我的设置中删除了 DEFAULT_AUTHENTICATION_CLASSES 并添加了这个:

 REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'users.auth.LoginSerializer'
 }

然后我复制粘贴了original serializer 并修改了函数_validate_email:

def _validate_email(self, email, password):
    user = None

    if email and password:
        user = self.authenticate(email=email, password=password)

        # TODO: REMOVE ONCE ALL USERS HAVE BEEN TRANSFERED TO THE NEW SYSTEM
        if user is None:
            password_hashed = hashlib.md5(password.encode())
            password_hashed = hashlib.sha256(password_hashed.hexdigest().encode())
            try:
                user = User.objects.get(email=email, password=password_hashed.hexdigest())
            except ObjectDoesNotExist:
                user = None
    else:
        msg = _('Must include "email" and "password".')
        raise exceptions.ValidationError(msg)

    return user

【讨论】: