• JWT登录与多方式登录


    JWT登录


    • urls
    from django.urls import path
    from user import views
    from rest_framework_jwt.views import obtain_jwt_token
    
    urlpatterns = [
        path('login/', obtain_jwt_token),
    ]
    
    • views
    # JWT登录
    def Login_return(token, user=None, request=None, role=None):
        '''
        :param token:   jwt 生成的token值
        :param user:    User对象
        :param request:     请求
        :return:
        '''
        if user.first_name:
            name = user.first_name
        else:
            name = user.username
    
        return {
            'authenticated': 'true',
            'id': user.id,
            'role': role,
            'name': name,
            'username': user.username,
            'email': user.email,
            'token': token,
        }
    
    • settings
    # jwt载荷中的有效期设置
    JWT_AUTH = {
        # 1. token前缀:headers中 Authorization 值的前缀
        'JWT_AUTH_HEADER_PREFIX' : 'JWT',
        # 2. token有效期:一天有效
        'JWT_EXPIRATION_DELTA' : datetime.timedelta(days=1),
        # 3. 刷新token:允许使用旧的token换新token
        'JWT_ALLOW_REFRESH': True,
        # 4. token有效期:token在24小时内过期,可续期token
        'JWT_REFRESH_EXPIRATION_DELTA':datetime.timedelta(hours=24),
        # 5. 自定义JWT载荷信息:自定义返回格式,需要手工创建
        'JWT_RESPONSE_PAYLOAD_HANDLER' : 'user.views.Login_return',
    }
    

    多方式登录


    • urls
    from django.urls import path
    from user import views
    from rest_framework_jwt.views import obtain_jwt_token
    
    urlpatterns = [
        path('login/', obtain_jwt_token),
    ]
    
    • views
    # 多方式登录
    class JJAuth(ModelBackend):
        def authenticate(self, request, username=None, password=None, **kwargs):
            try:
                user = User.objects.get(Q(username=username) | Q(phone=username) | Q(email=username))
            except Exception as e:
                return None
            if user is not None and user.check_password(password):
                return user
    
    • settings
    # 自定义验证后端
    AUTHENTICATION_BACKENDS = ['user.views.JJAuth']
    
  • 相关阅读:
    大道至简第四章读后感
    JAVA类与对象
    大道至简第三章读后感
    JAVA语法基础 动手动脑及课后作业
    课程作业01
    大道至简第二章读后感
    大道至简第一章读后感
    swift学习笔记之-自动引用计数
    swift学习笔记之-继承
    swift学习笔记之-闭包
  • 原文地址:https://www.cnblogs.com/zj555/p/13939136.html
Copyright © 2020-2023  润新知