A detailed explanation of how the generated token of jwt authentication is passed back to the backend and parsed

token backend parsing after jwt authentication generation

First, the front end sends the token

The location of token headers

{'authorization': value of token ', content type': application / JSON}

Write in ajax

//Show only part of the headers code
//token value is usually put in cookies
//The default for ajax submission is json format. You don't need to declare js format

2. The backend accepts and resolves the token

1. First define authentication classes

from rest_framework.exceptions import AuthenticationFailed
import jwt
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import get_authorization_header
class JWTAuthentication(BaseJSONWebTokenAuthentication):
    # Custom authentication class, override the authenticate method
    def authenticate(self, request):
        # Pass authentication, return user, auth
        # Authentication failed, return None
        # auth = request.META.get('HTTP_AUTHORIZATION')  # The front desk carries the token with auth
        # Get auth from the request header sent from the front desk
        auth = get_authorization_header(request)
        if not auth:
            raise AuthenticationFailed('Authorization Field is required')
            payload = jwt_decode_handler(auth)

        # In case of jwt parsing exception, throw an exception directly to represent the illegal user, or return None to handle as a tourist
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('token Expired')
            raise AuthenticationFailed('token illegal')

        user = self.authenticate_credentials(payload)
        return (user, auth)

On several methods

  • auth = request.META.get('HTTP_AUTHORIZATION ') get the string format of token
  • Auth = get ABCD authorization ABCD header (reuqest object) gets the binary format of token
  • JWT · decode · handler (binary format of token)
    • If the token does not expire: return user information
    • If the token expires: throw an exception, the expired exception is jwt.ExpiredSignature
  • Authenticate ﹣ credentials (JWT ﹣ decode ﹣ handler parsed information) returns the user object

2. Call user authentication class locally

#Rating and certification
from rest_framework.throttling import SimpleRateThrottle

class SMSRateThrottle(SimpleRateThrottle):
    scope = 'sms'    #This is a variable name given for global settings
    # Only restrict the get method of submitting mobile number
    def get_cache_key(self, request, view):
        mobile = request.query_params.get('mobile')
        # No cell phone number, no frequency limit
        if not mobile:
            return None
        # Return a string that can dynamically change according to the phone number and is not easy to repeat, as the key of operation cache
        return 'throttle_%(scope)s_%(ident)s' % {'scope': self.scope, 'ident': mobile}
class Test(APIView):
    authentication_classes = [Our custom user authentication class] #Such as [JWTAuthentication]
    #To determine whether the information of the login account is a normal user or a tourist
    permission_classes =[IsAuthenticated] 
    #Grant authority
    #AllowAny: allow all
    #IsAuthenticated: only login users are allowed
    #IsAuthenticatedOrReadOnly: read only for tourists, unlimited login users
    #IsAdminUser: background user or not
    DEFAULT_THROTTLE_RATES = [Frequency certification]#Such as [SMSRateThrottle]
    #Partial rating certification
    #The following operations can only be performed if the permissions given above are met

3. Call user authentication class globally

In setting.py

#drf configuration
AllowAny: Allow all users
IsAuthenticated: Allow only logged in users
IsAuthenticatedOrReadOnly: Read only for tourists, unlimited login users
IsAdminUser: Background user or not
        # django default session verification: verification rules for tourists and login users
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.permissions.AllowAny',
        # Global configuration: one stop website (all operations need to be logged in before access)
        # 'rest_framework.permissions.IsAuthenticated',
        'user': '5/min',  # Logged in users can access 5 times a minute
        'anon': '3/min',   # Visitors can visit three times a minute
        'sms': '1/min'     #Once a minute for the same cell phone

jwt To configure
import datetime
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=1000), #Valid period of token generation

Tags: Python Mobile JSON Django Session

Posted on Wed, 06 Nov 2019 09:23:26 -0500 by Keith Scott