Authentication using authentication separated front and rear ends JWT

Certification Category

Certification is divided into RBAC and we Django Auth is RBAC

RBAC So what is it? It is role-based access control

Such a table is provided and is divided into 3 Table 5 Table 6 Table

Table Design

 

 Table 5 produced many-CAUSE

 

One is to have some exceptional user permissions, does not depend on the identity of the table

This table is django

Correspondence between the corresponding user and the identity and authority of which indicate which user group permissions which

Permissions table analysis Considerations

Because the user there is also the other fields need to inherit and tell DJango use its own user list

If after that time no longer use the database migration so be sure to inherit AsbrUser before migrating

 

JWT

Although certification do not have to check a database session, but the server encountered when landing registered or need to generate session and save, also need io operation 

Have to go check session so we simply do not check the

 

So with the second JWT

You gave me the information I give you a token is generated by the algorithm, next time you ask me, you take the token

Next time you asked me when I take this token is decrypted, if there is no problem I'll let you through

jwt shortcomings

JWT once issued, will always be valid for such period

JWT use

# Download 
PIP djangorestframework- the install JWT 

#post successful login request returns token 
from django.urls Import path
 from rest_framework_jwt.views Import obtain_jwt_token 
the urlpatterns = [ 
    path ( ' Login / ' , obtain_jwt_token), 
] 

# use their own return token method Import datetime JWT_AUTH = { # expiration time ' JWT_EXPIRATION_DELTA ' : the datetime.timedelta (Days =. 1 ), # custom authentication result: see below and custom serialization user Response 'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler', }

Custom return token (you can re-write your own util module because it is public)

from .serializers import UserModelSerializers
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserModelSerializer(user).data
    }
from rest_framework import serializers
from .models import User
class UserModelSerializer(serializers.ModelSerializer):
    """轮播图序列化器"""
    class Meta:
        model = User
        fields = ["username", "mobile"]

Start the authentication user / authentications.py (create your own)

import jwt
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import get_authorization_header
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
        def authenticate(self, request):
            # 采用drf获取token的手段 - HTTP_AUTHORIZATION - Authorization
            token =get_authorization_header (Request)
             IF  not token:
                 The raise AuthenticationFailed ( ' the Authorization field is required ' )
             # you can add pocketing measures: The original function is token prefix 

            # DRF-certified calibration algorithm jwt 
            the try : 
                payload = jwt_decode_handler (token)
             the except jwt .ExpiredSignature:
                 The raise AuthenticationFailed ( ' signature expired ' )
             the except jwt.InvalidTokenError:
                 The raise AuthenticationFailed ( ' illegal user ') 
            User = self.authenticate_credentials (payload)
             # authentication result of the lost DRF 
            return User, token

Global Configuration local configuration

REST_FRAMEWORK = {
    # 认证模块
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'user.authentications.JSONWebTokenAuthentication',
    ),
}

# Disable local
authentication_classes = []

 
 

# 局部启用
from user.authentications import JSONWebTokenAuthentication
authentication_classes = [JSONWebTokenAuthentication]

 

Multi-Log

Configuration

AUTHENTICATION_BACKENDS = ['user.utils.JWTModelBackend']
from django.contrib.auth.backends import ModelBackend
from .models import User
import re
class JWTModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        :param request:
        :param username: 前台传入的用户名
        :param password: 前台传入的密码
        :param kwargs:
        :return:
        """
        try:
            if re.match(r'^1[3-9]\d{9}$', username):
                user User.objects.get = (Mobile = username)
             elif re.match (R & lt ' .. * @ * ' , Username): 
                User = User.objects.get (In Email = username)
             the else : 
                User = User.objects.get ( = username username)
         the except User.DoesNotExist:
             return None   # authentication failure to return None, jwt can not delete token 
        # user exists, through password verification, user is alive is_active field 1 
        IF the user and user.check_password (password ) and self.user_can_authenticate (the User):
             return the User  # Authentication returned to the user to generate a token jwt

 

 

  

 

Guess you like

Origin www.cnblogs.com/xzqpy/p/11209544.html