ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python-创建自定义身份验证

2019-12-11 03:56:47  阅读:218  来源: 互联网

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


我正在将数据库传输到新项目,更确切地说是用户.
不要问我为什么,但是旧数据库中的密码先用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-3-x,django-rest-framework,django-rest-auth,python,django
来源: https://codeday.me/bug/20191211/2106456.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有