python - 创建自定义身份验证

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

我正在将数据库转移到新项目,更准确地说是用户。 不要问我为什么,旧数据库中的密码先用 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."
    ]
}

你有什么想法吗?也可能我做错了。

提前谢谢你。

杰里米。

最佳答案

遵循 @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

关于python - 创建自定义身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54580020/

相关文章:

django - Pandas -分组和聚合列中具有相同值的连续行

python - 使用 redis-py(redis 上的 python 包装器)与远程 redis 服务器通信

python - 符号简化以最少数量的加法和乘法运算

python - @classmethod 没有调用我的自定义描述符的 __get__

Django - UpdateView 中的动态 success_url

python - 从流中产生的正确方法是什么?

python - 如何使用 Django choicefield 动态设置选项?

python - 如何修复 'Can' t 在 'localhost:3306' 错误上连接到 MySQL 服务器

python - 为什么我的简单前馈神经网络发散(pytorch)?

python - 如何在 Python 中将数据附加到嵌套 JSON 文件