What is the JWT authentication mechanism?

1. JWT:

After a user registers or logs in, we want to record the user's login status, or create authentication credentials for the user. We no longer use the Session authentication mechanism, but the Json Web Token authentication mechanism.
1. What is JWT:

Json web token (JWT), is a JSON-based open standard ((RFC 7519) implemented for passing claims between web application environments. The token is designed to be compact and secure, especially suitable for single Sign-on (SSO) scenario. JWT claims are generally used to transfer authenticated user identity information between identity providers and service providers, so as to obtain resources from resource servers, and can also add some additional business logic necessary The statement information of the token can also be directly used for authentication or encrypted.
1.1 Origin:

Speaking of JWT, we should talk about the difference between token-based authentication and traditional session authentication.

1.1.1 Traditional session authentication:

We know that the http protocol itself is a stateless protocol, which means that if the user provides a user name and password to our application for user authentication, the user will have to perform user authentication again when the next request is made. OK, because according to the http protocol, we don't know which user made the request, so in order for our application to identify which user made the request, we can only store a copy of the user's login information on the server. This login information It will be passed to the browser in the response, telling it to save it as a cookie, so that it can be sent to our application when the next request is made, so that our application can identify which user the request came from. This is the traditional session-based authentication.

However, this session-based authentication makes the application itself difficult to expand. With the increase of different client users, an independent server can no longer carry more users. At this time, the problem of session-based authentication applications will be exposed. Based
on Problems revealed by session authentication
session: After each user is authenticated by our application, our application must make a record on the server side to facilitate the identification of the user's next request. Generally speaking, the session is stored in memory. With the increase of authenticated users, the overhead of the server will increase significantly.
Scalability: After the user is authenticated, the server records the authentication. If the authentication record is stored in the memory, it means that the next request of the user must be made on this server, so that the authorized resource can be obtained. In distributed applications, the capacity of the load balancer is correspondingly limited. This also means that the scalability of the application is limited.
CSRF: Because user identification is based on cookies, if cookies are intercepted, users will be vulnerable to cross-site request forgery attacks.

1.1.2 Token-based authentication mechanism:

The token-based authentication mechanism is similar to the HTTP protocol and is also stateless. It does not need to retain the user's authentication information or session information on the server side. This means that the application based on the token authentication mechanism does not need to consider which server the user logs in, which facilitates the expansion of the application.

The process is like this:

The user uses the username and password to request the server
server to verify the user's information.
The server sends a token to the user through verification
. The client stores the token and attaches the token value to each request.
The server verifies the token value and returns data.
The token must be To be passed to the server every time a request is made, it should be stored in the request header. In addition, the server must support the CORS (Cross-Origin Resource Sharing) strategy. Generally, we can do this on the server. Access-Control-Allow- Origin: *.

2. What does JWT look like?

JWT is composed of three pieces of information, and these three pieces of information text are linked together to form a Jwt string. like this:

Composition of eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh

:1H JWgT2

The first part we call it the header;
the second part we call it the payload (similar to the items carried on the plane);
the third part is the visa (signature).

2.1.1 header:

The header of jwt carries two parts of information:

Claim type, here is the jwt
claim encryption algorithm usually directly use HMAC SHA256
The complete header is like the following JSON:
{   'typ': 'JWT',   'alg': 'HS256' } Then base64 the header Encryption (the encryption can be decrypted symmetrically), forming the first part




eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

2.1.2 payload

In and is where valid information is stored. The name seems to specifically refer to the goods carried on the plane. These effective information contain three parts

Statements registered in the standard

public statement

Private declarations
Declarations registered in the standard (recommended but not mandatory):

iss: jwt issuer

sub: the user for which jwt is oriented

aud: the party receiving jwt

exp: The expiration time of jwt, which must be greater than the issue time

nbf: Define before what time, the jwt is not available.

iat: the issuance time of jwt

jti: The unique identity of jwt, which is mainly used as a one-time token to avoid replay attacks.
Public statement: Public statement can add any information, generally add user-related information or other necessary information for business needs. However, it is not recommended to add sensitive information, because this part can be decrypted on the client.

Private statement: A private statement is a statement jointly defined by the provider and the consumer. It is generally not recommended to store sensitive information, because base64 is symmetrically decrypted, which means that this part of the information can be classified as plaintext information.

Define a payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

2.1.3 signature

The third part of JWT is a visa information, which consists of three parts:

The header (after base64)
payload (after base64)
secret
needs to use the base64-encrypted header and the base64-encrypted payload. Connect the strings, and then use the encryption method declared in the header to encrypt the combination of secret and salt. Then it constitutes the third part of jwt.

// javascript
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);

var signature = HMACSHA256(encodedString, 'secret'); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

uses . to connect these three parts into a complete string to form the final jwt:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

How to apply:

Generally, Authoriztion is added to the request header, and the Beaer annotation is added:

fetch('api/user/1', {
  headers: {
    'Authorization': 'Bearer ' + token
  }
})

The server will verify the token, and if the verification is passed, the corresponding resource will be returned. The whole process is like this:


4. Summary

4.1 Advantages

Because of the versatility of json, JWT can support cross-language, such as JAVA, JavaScript, NodeJS, PHP and many other languages ​​can be used.
Because of the payload part, JWT can store some non-sensitive information necessary for other business logic in itself.
Easy to transfer, the composition of jwt is very simple, and the byte occupation is very small, so it is very easy to transfer.
It does not need to save session information on the server side, so it is easy to apply the extension
4.2 security related

Sensitive information should not be stored in the payload part of jwt, because this part is the part that can be decrypted by the client.
Protect the secret private key, which is very important.
If possible, please use https protocol
2, Django REST framework JWT:

After verifying the user's identity (checking the user name and password), we need to issue a JWT to the user, and when we need to use the user's identity information, we also need to verify the user's JWT.
Regarding the issuance and verification of JWT, we can use the Django REST framework JWT extension to complete.
Documentation website: http://getblimp.github.io/django-rest-framework-jwt/

1. Installation configuration:

Install:

pip install djangorestframework-jwt
Placement:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
# JWT_EXPIRATION_DELTA specifies the validity period of the token

2. use

The documentation of the Django REST framework JWT extension provides a method for manually issuing JWT:

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)

After the registration is successful, China Unicom returns the token, which needs to be created in the registration view.
Modify the CreateUserSerializer serializer and add a method of manually creating tokens in the create method

from rest_framework_jwt.settings import api_settings
class CreateUserSerializer(serializers.ModelSerializer):
    """
    Create user serializer
    """
    ...
    token = serializers.CharField(label='login status token', read_only=True) # Add token field
    class Meta:
        ...
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')  # 增加token
        ...
    def create(self, validated_data):
        """
        create user
        """
        # Remove properties that do not exist in the database model class
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = super().create(validated_data)
        # Call django's authentication system encryption password
        user.set_password(validated_data['password'])
        user.save()
        # Supplementary generation of token to record login status
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user

To save the token at the front end,
we can save the JWT in the cookie, or in the local storage of the browser, we save it in the local storage of the browser

The browser's local storage provides sessionStorage and localStorage:

sessionStorage
expires
when the browser is closed


localStorage. variable name = variable value // save data
localStorage. variable name // read data
localStorage.clear() // clear all data saved in localStorage

Add save token to the front-end js/register.js file

var vm = new Vue({
    ...
    methods: {
        ...
        on_submit: function(){
            axios.post(...)
                .then(response => {
                    // record the user's login status
                    sessionStorage.clear();
                    localStorage.clear();
                    localStorage.token = response.data.token;
                    localStorage.username = response.data.username;
                    localStorage.user_id = response.data.id;
                    location.href = '/index.html';
                })
                .catch(...)
        }
    }
})

 

Guess you like

Origin blog.csdn.net/leaf__yang/article/details/122860542