This article mainly introduces two schemes of user status Persistence: Session and effect_token, as well as the implementation methods of these two schemes, as well as the advantages and disadvantages comparison.
Introduction: HTTP is a stateless protocol, which means that if the user provides the user name and password for user authentication to our application, the next request, the user must perform another user authentication.
According to the stateless nature of the HTTP protocol, we do not know which user sent the request in the next request, so in order to let us identify which user sent the request, you must use some special methods, such as session and cmdt_token.
I. Session
Based on the above application, I can use session to save the user's logon status. Django provides the session storage mechanism by default and starts the session by default.
Session storage: database, local cache, and hybrid storage. Generally, local cache is used:
SESSION_ENGINE=‘django.contrib.sessions.backends.cache‘
How can we maintain the user logon status?
After the user logs on or registers successfully, set the session.
Class userview (apiview ):...... # implement the business logic request for user login or registration. session ['user _ id'] = user. id request. session ['is _ login'] = true ..... # response
Because the session is saved on the server, a random string (sessionid) is generated when the session is set and sent to the client through cookie, the server side uses sessionid as the key and stores the encrypted calculated parameter length string as the value on the server side.
For more information about the session storage mechanism, see: https://www.cnblogs.com/lenther2002/p/4822302.html
Disadvantages:
- Session: after each user passes our application authentication, our application must make a record on the server to facilitate the user's next request identification. Generally, the session is stored in the memory, as the number of authenticated users increases, the overhead of the server will increase significantly.
- Scalability: After user authentication, the server makes authentication records. If the authentication records are stored in the memory, this means that the next request must be sent to this server, in this way, the authorized resources can be obtained. In this way, the capacity of the Server Load balancer is limited in distributed applications. This also limits the scalability of applications.
- Csrf: because it is based on cookies for user identification, if a cookie is intercepted, the user will be vulnerable to cross-site request forgery attacks.
Ii. effect_token
The token-based authentication mechanism is similar to the HTTP protocol and is stateless. It does not need to retain user authentication information or session information on the server. This means that applications based on the Token Authentication Mechanism do not need to consider which server the user is logged on to, which facilitates application expansion.
The basic process is as follows:
- If the user logs on or registers successfully, the server returns a token.
- The client stores the token (which can be stored in cookies or local disks)
- Each request carries this token Value
- The server verifies the token value (Django extension provides the effect_token authentication mechanism) and returns data.
1. What is JWT?
JWT consists of three pieces of information..
Link together to form a JWT string. Like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
2. Its composition is as follows:
1. header-header, mainly used to declare the type, which is JWT. And declare the encryption algorithm, usually HMAC sha256.
2. Payload: loads, stores the declarations (issuer, receiver, etc.) registered in the standard, and adds user information.
3. signature -- visa, which requires base64-converted header and base64-encoded Payload.
Connect to a string and use the encryption method declared in the header.Secret_key
Combined encryption to obtain signature.
Note:
- Do not store sensitive information in payload, because this part of information is only replaced with base64 instead of encrypted.
- Do not expose secret_key. If exposed, you can generate JWT Based on the header and payload.
3. Its implementation mechanism is as follows:
That is, each time a user requests to carry this token, Django will retrieve the header and payloads parts for authentication, in addition, the secret key secret_key of Django is encrypted using the encryption method declared in the header to generate a new signature2. The third part of the token carried by the user is compared with signature1, if the user modifies the token, the generated signature2 is inconsistent with the signature1 carried by the user, the verification fails.
1. Whether a token exists determines whether JWT authentication is performed.
2. the correctness of the token determines whether JWT authentication can be performed.
Advantages:
- Because of the versatility of JSON, JWT supports cross-language support, such as Java, JavaScript, nodejs, PHP, and many other languages.
- With payload, JWT can store some non-sensitive information necessary for other business logic.
- It is easy to transmit. JWT has a very simple structure and occupies a small number of bytes, so it is very easy to transmit.
- It does not need to save session information on the server, so it is easy to expand applications.
Implementation:
1. installation:
pip install djangorestframework-jwt
2. Configuration
Rest_framework = {'default _ authentication_classes ': ('rest _ framework_jwt.authentication.jsonwebtokenauthentication', 'rest _ framework. authentication. sessionauthentication ', 'rest _ framework. authentication. basicauthentication ',),} # effect_expiration_delta indicates the token validity period. effect_auth = {'jwt _ expiration_delta': datetime. timedelta (days = 1 ),}
3. Implementation
Class userview (apiview ):....... # business logic for registration or login # generate token t_payload_handler = login into t_encode_handler = login payload = login t_payload_handler (User) token = login t_encode_handler (payload) user. token = token ....... # response
Note: prerequisites:
This token must be passed to the server during each request. It should be stored in the request header. In addition, the server must supportCORS (cross-source Resource Sharing)
Policy. We can do this on the server.Access-Control-Allow-Origin: *
.
Because the Default Authentication class we configured previously includes:
‘DEFAULT_AUTHENTICATION_CLASSES‘: ( ‘rest_framework_jwt.authentication.JSONWebTokenAuthentication‘, )
Therefore, the user carries a token in each request. The Django authentication system automatically authenticates the token. If the authentication succeeds, the user authentication is completed.
Over ~~~, This article briefly introduces two commonly used methods for maintaining user logon status ~~~, Not all sessions are introduced. I have the opportunity to add more information ~~~
Maintenance of user logon status in DRF framework