token backend parsing after jwt authentication generation

Keywords: Python Mobile JSON Django Session

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
headers:{"authorization":this.$cookies.get("token")}
//token value is usually put in cookies
//The default 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')
        try:
            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')
        except:
            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 the 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
"""
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # django default session verification: verification rules for tourists and login users
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'api.authentications.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        # 'rest_framework.permissions.AllowAny',
        # Global configuration: one stop website (all operations need to be logged in before access)
        # 'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_THROTTLE_RATES': {
        '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_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=1000), #Valid period of token generation
    'JWT_AUTH_HEADER_PREFIX': 'TOKEN',
}

Posted by marklarah on Mon, 28 Oct 2019 07:05:12 -0700