This article records my understanding of django Learning and understanding of authentication
On the first code
# Backend It can be ordinary python class , However, the login verification needs to have the following provisions 2 A way ( Sign in basic authentication # BasicAuthentication The following back-end processing logic - It can also be understood as middleware ):
# authenticate(self,username=None,password=None) perhaps authenticate(self,token=None), If it passes the verification , The return value is one User object , If it doesn't pass the verification , The return value is None.
# get_user(self,user_id)
# The specific use of these two methods is not the same , About login verification authenticate,Django When using them , Will traverse all auth backends
# Once you find one backend Check by , Return User object , Then it will stop below backend The check , And will verify the successful backend Bind to the user session in ,
# After that, if you call the method again , Then it will use session Medium backend check , Instead of traversing all backend 了 .
AUTHENTICATION_BACKENDS = ['util.auth_func.CustomBackend']
REST_FRAMEWORK = {
# api file
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema',
# Configure the default authentication method base: Account password verification
# session:session_id authentication
'DEFAULT_AUTHENTICATION_CLASSES': (
# drf This is the main stage of verification ,middleware Of auth It's mainly about setting up session and user To request object
# The default validation is top-down validation according to the validation list ( Just pass one )
# Judge request Whether there is JWT Custom request header for (token form )
'rest_framework_simplejwt.authentication.JWTAuthentication',
# To determine if there is session_id(cookie form )
'rest_framework.authentication.SessionAuthentication',
# basic authentication ( User password login )
'rest_framework.authentication.BasicAuthentication',
)}
AUTHENTICATION_BACKENDS When you log in, you will call ( Priority level )
DEFAULT_AUTHENTICATION_CLASSES
I have written three verification methods here But if you can match any one , Whether it's successful or not , Will not continue to verify
first stage :rest_framework_simplejwt.authentication.JWTAuthentication
With postman For example , Because my login verification is priority jwt, So I fill in the parameters token In the form of Just go JWTAuthentication
Level second :rest_framework.authentication.SessionAuthentication -- Check request Whether there is session_id
Level third :rest_framework.authentication.BasicAuthentication --basic authentication , It's the account and password
So much is written in this issue Record again when you have time . I saw a sequence diagram before Also quite good I'll stick it down