JWT related learning (pure natural handwriting)

JWT (Json Web Token) is a token authentication method, compared with the traditional session authentication method.

1. Why do you need certification?

A system, if you want to use its functions, it is necessary to perform a login operation, log in to verify the user name and password, and transmit it through the HTTP communication protocol, but the HTTP protocol is a stateless protocol. If the HTTP communication after login is not authenticated, then any unlogged Everyone can visit. Therefore, authentication is required to prevent such a thing from happening.

 

Second, the traditional session authentication method has the following disadvantages:

1. After the user logs in, the session needs to be stored in the server. When a large number of users log in, the server will store a large number of sessions. The disadvantage is that it takes up a lot of resources.

2. If the server session storage location is memory, it will affect the load balancing.

3. The client stores the session in the cookie, and if others get the cookie, it can be forged.

 

3. Advantages of jwt

1. The server does not need to store jwt and does not need to occupy a lot of resources.

2. jwt is in json format, which occupies a small amount of traffic.

3. Because there is no state and no storage, it does not affect load balancing at all.

 

Fourth, JWT description:

JWT is divided into three parts, head (header), payload (payload) and signature.

The header indicates the algorithm type (mostly fixed) and uses Base64 for encoding. The payload stores the transmitted information and uses Base64 for encoding. For our system, it is the JSON string of the JwtUser object and the expiration time (we The system is currently 24 hours).

The signature means that after the above-mentioned head and payLoad perform the Base64 string connection, salt is added, and the combination is encrypted. The salt is stored in the server. For our system, it is stored in the server configuration file.

The final result is the Base64 encoding result of the head header + ',' + the Base64 encoding result of payLoad + ',' + signature.

 

5. Implementation method:

Use jjwt to implement (code and quickStart can be viewed on GITHUB)

 

6. Transmission method:

The client http protocol calls access, and the access system RPC protocol calls the account system. If the account system is successfully logged in, it will generate a jwt and return it to the access system. The access system will return the jwt string to the client. The user's http calls all add this jwt string to the http request header. After the access receives the jwt, it will be parsed. If there is an error in the parsing, an exception will be thrown and no operation will be performed. If the JWT is OK, continue.

 

Reference: http://www.jianshu.com/p/576dbf44b2ae

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326297127&siteId=291194637