Enjoy learning class guest author: Lao Gu

Reprint please state the source!

preface

In the last article “Distributed Session under micro-service Architecture”, we introduced the implementation of Session. In this article, we will know what is JWT? And JWT to implement distributed sessions.

What is the JWT

JWT stands for JSON Web Token

1. The data is in JSON format

2. Used for Web applications

Is a Token, that is, a Token mode

Take a look at the official description, which defines a compact and self-contained way to securely transfer information between parties as JSON objects. The information can be signed symmetrically or asymmetrically to prevent the information from being changed in series.

Compact means that the JWT is small and the amount of data is not large. The data can be transmitted through URLS, POST parameters, or Header request headers. Self-contained meaning: JWT allows users to customize the user information contained in the JWT, such as name, nickname, etc. (do not put secret information). This avoids multiple queries to the database.

JWT data structure

JWT consists of three parts

1, the Header

2, Payload

3, Signature

All three together

Header.Payload.Signature
Copy the code

case

If it doesn’t look messy, let’s take a look at the structure in turn.

Header

This is the first section of JWT data, which represents the header information and mainly describes the metadata of JWT. The case above is as follows:

{
 alg: "HS256",
 typ: "JWT"
}
Copy the code

1. The ALG attribute represents the signature algorithm. The default algorithm is HS256, and you can use other algorithms by yourself.

2. The typ attribute indicates the type of the token, and the JWT token is JWT.

The JSON data above will be encoded using the Base64 algorithm, see the tool diagram

Payload

This is the second section of JWT data, which is used to store the actual data to be transferred. JWT also officially specifies 7 fields to choose from

Of course, except for the official field, we can customize the field. In the case above, let’s take a look at the actual data

Note: this section is also Base64. JWT is not encrypted by default and anyone can access it by Base64 decoding, so do not put hidden information in JWT

Signature

This is the third section of JWT data, which is mainly used to sign the data of the first two sections to prevent data tampering. In general, we will have a secret when signing, only the server knows, and then use the signature algorithm in the Header to sign, the formula is as follows:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret)
Copy the code

After calculating the Signature, combine the Header, Payload, and Signature parts into a string and use (.) between them. Delimit, so that the combined string can be returned to the user.

The way JWT works

When the user authenticates and logs in, the server returns a JWT to the client. Then this JWT is the user’s certificate, and we will carry this certificate token wherever we go in the future. JWT is usually placed in the Authorization header, especially when accessing protected resources. Bearer Schema is used, as in header request headers:

Authorization: Bearer <token>
Copy the code

Jwt-based authentication

The way JWT works above is actually a complete identity authentication process, which we will talk about in a more general way.

1. The user provides the user name and password for login

2. The server verifies whether the user is correct. If the user is correct, the server returns a token to the client, which can contain user information

3. The client stores the token in a cookie or local storage

4. When the client requests something from now on, it will always carry this token and put it in the request header

5, the server determines whether there is a token, and after decoding, it can know which user it is

6. The server can then return information about the user

In this process, have you noticed that the user information is stored in JWT and in the client (cookie, local storage), and the server only needs to decode and verify, so that it can know and obtain the user information? The way we used to do sessions was different.

Different from session-cookie

Session-cookie mode is not covered here, as it has been covered in previous articles. The diagram above illustrates the difference

The figure above shows Sesson server mode. We find that Session user information is stored on the server side. Let’s look at the JWT

The tokens above are stored in the client, and the server only needs to decode them.

Benefits of JWT authentication

1. Since the token is stored on the client, the server is only responsible for decoding. This eliminates the need to consume server-side resources.

2. The server side can be infinitely scalable. The load balancer can transfer users to any server and the server can know the user information because it is contained in JWT.

3, data security, because there is a signature, to prevent tampering, but the information is transparent, do not put sensitive information.

4, put in the request header submission, good protection against CSRF attack,

With all these benefits in mind, is JWT a good place to replace the Session mode?

Disadvantages of the JWT approach

1. Token invalidity

The biggest disadvantage of JWT is that it cannot actively invalidate the token. Some people will say that the token has an expiration date. Yes, the token itself has an expiration date, but once the token is issued, the server cannot retrieve it.

For example, the validity period of a JWT token is 3 days, but we found that this token is abnormal, and it may be logged in, then the real user can change the password. However, even if the password is changed, the abnormal token is still valid, because our server cannot actively invalidate the abnormal token before the expiry time of 3 days.

2. Data delay and inconsistency

Another problem is that the JWT contains part of the user’s information. If these parts of the information are modified, the server still obtains the user information in the previous JWT, resulting in inconsistent data.

conclusion

How do you choose the Session mode? Do you choose the traditional Sesion-Cookie server mode or JWT mode? It depends on the specific collection business. However, it is recommended to use the traditional method, because future business will most likely use user sessions. Ok, thanks!!

Stay with me and share more.