Jwt configuration of the project django token to log 2

1, the installation jwt                                                                                                   

pip install djangorestframwork-jwt

2, modify the configuration file dev.py                                                                              

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}
import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),    # 设置jwt的认证过期时间
}

3, the registered route                                                                                                

from rest_framework_jwt.views Import obtain_jwt_token 

the urlpatterns = [ 
    path ( ' Login / ' , obtain_jwt_token), # JWT provides an authentication, can be used directly after introduction view obtain_jwt_token 
]

4, this case can be used to test interface postman                                                      

 

 

     As FIG i.e., background interface is ok

 

5, jwt return provides only a token return, if you want to return other fields, the need for reform   

  Then the corresponding module file utils following method rewritten jwt_response_payload_handler

def jwt_response_payload_handler(token, user=None, response=None):   # 如果不知道为啥要带这三个参数,可以ctrl+shift+f全局搜索,再jwt得post方法有
    """
    自定义jwt认证成功返回对象
    :param token: token
    :param user: 用户对象
    :param request:
    :return: 用户token,id,户名username,用户头像
    """
    return {
        "id": user.id,
        "username": user.username,
        "avatar": user.avatar.url,
        "token": token,
        "nickname": user.nickname
    }

   修改配置文件dev.py,指定处理得方法:

JWT_AUTH = {
    ...
    "JWT_RESPONSE_PAYLOAD_HANDLER": "users.utils.jwt_response_payload_handler",
}

 

6、如下图返回结果,即为改造成功                                                                  

 

 

 

7、改造authentication 实现多条件登录                                                      

  django.auth提供得登录,仅限于使用username 和password 进行认证登录,如果想要使用多条件(例如:手机号+密码; 邮箱+密码)登录,此时需要改写authentication方法

  django.auth得认证可以查看:from django.contrib.auth.backends import ModelBackend得authentication方法

  在模块(users)得utils文件中重新写

from django.contrib.auth.backends import ModelBackend
from .models import User
from django.db.models import Q


def get_user_by_other_info(account):
    """
    根据不同的账号类型来获取用户
    :param username:  用户信息,可以是用户名,也可以是邮箱或者手机号码
    :return:
    """
    try:
        user = User.objects.get(Q(username=account) | Q(mobile=account) | Q(email=account))
    except User.DoesNotExist:
        user = None
    return user


class UserInfoModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写authentication, 以支持多条件登录
        :param request:
        :param username: 用户名或者手机号码或者用户邮箱
        :param password:  登录密码
        :param kwargs:
        :return: 认证后的用户对象
        """
        user = get_user_by_other_info(username)
        if isinstance(user, User) and user.check_password(password) and self.user_can_authenticate(user):
            return user

   修改配置文件,指定authenticate处理方法:

AUTHENTICATION_BACKENDS = [
    "users.utils.UserInfoModelBackend",
]

 

8、出现下图,则多条件登录,后端配置成功                                                                

Guess you like

Origin www.cnblogs.com/shangguanruoling/p/12157121.html