JWT brief introduction

This is the back-end small class of the monastery. Each article is shared from

[background introduction] [knowledge analysis] [common problems] [solutions] [coding practice] [extended thinking] [more discussion] [References]

Eight aspects of in-depth analysis of back-end knowledge / skills. This article shares:

[JWT brief introduction.]

Hello, I'm he Shuang, the 11th student of Zhengzhou branch of it Academy. I'm an honest, pure and kind-hearted back-end programmer. Today, I'd like to share with you a brief introduction to JWT, the knowledge point in deep thinking, Java (career) task 5 on the official website of the Academy.

1. Background introduction

Since most microservices are distributed and need to be deployed by several servers, when a user logs in to one of the servers, the traditional way is to save his login information in session, and then use shared storage sharing, such as redis sharing. The disadvantage of this scheme is that the shared storage needs a certain protection mechanism, so it needs to be accessed through a secure link, At this time, the implementation of the solution is usually quite complex, so the token based login is used here.

What is JWT?

JWT (JSON web token): JSON network token. JWT is a portable secure cross platform transmission format, which defines a compact self-contained way to safely transmit information between different entities (JSON format).

It is a standard for transferring data between two entities in the web environment. In fact, what is transmitted is a string.

Broadly speaking, JWT is a standard name; In a narrow sense, JWT refers to the token string used to pass

2. Knowledge analysis

Structure of JWT:

JWT includes the use of Separated by three parts: header header header payload signature. The structure looks like this Payload. The header of signature JWT carries two parts of information

{"alg": "rs256", "typ": "JWT"} alg: declare the encryption algorithm typ: declare the type. Base64 the header information to get the header part

Payload is the main part, which means carrier. It carries effective JWT packets. It contains three parts

Standard declaration public declaration private declaration

Standard declared fields

Interface stantar {ISS?: string; / / the issuer of the JWT sub?: string; / / the user aud?: string; / / the party receiving the JWT exp?: number; / / the expiration time of the JWT NBF?: number; / / the JWT is available IAT?: number; / / the issuing time of the JWT JTI?: number; / / the unique identity of the JWT}

Publicly declared fields

interface Public { [key: string]: any; } Any information can be added to the public declaration field, but because it can be decrypted, do not store sensitive information.

Private declared fields

interface Private { [key: string]: any; } Private declaration is a field added by JWT provider. It can also be decrypted, so it can't store sensitive information.

Signature

The string obtained by base64url encoding the JSON structure corresponding to the header and payload is spliced with dot numbers, and then generated according to the signature algorithm specified by alg in the header, and then add your own set key for encryption signature.

JWT design single sign on system process:

Eight steps for user authentication

The so-called user authentication is a mechanism that allows users to log in and allow users to use their account when accessing the website in the next period of time without logging in again.

First, the server application (hereinafter referred to as "application") allows users to send their user name and password to the server interface through a web form. This process is generally an HTTP post request. The recommended method is to use SSL encrypted transmission (HTTPS protocol) to avoid sniffing sensitive information.

Next, the application checks the user name and password with the database.

After checking the user name and password successfully, the application takes the user's ID (user_id in the figure) as an attribute of JWT payload, performs Base64 coding and splicing with the header respectively, and then signs to form a JWT. The JWT here is a string with the shape of lll.zzz.xxx.

The application returns the JWT string to the user as part of the request cookie. Note that the httponly attribute must be used here to prevent cookies from being read by JavaScript, so as to avoid cross site scripting attacks (XSS attacks).

Before the cookie expires or is deleted, the application will receive the cookie containing JWT every time the user visits the application. Thus, the application can extract the JWT from the request.

The application checks the effectiveness of JWT through a series of tasks. For example, check whether the signature is correct; Check whether the token has expired; Check whether the receiver of the token is itself (optional).

After the application confirms that the JWT is valid, the JWT performs Base64 decoding (which may have been completed in the previous step), and then reads the user's ID value in the payload, that is, the user_id attribute. Here, the user's ID is 1025.

The application obtains the information of the user with ID 1025 from the database, loads it into memory, and initializes a series of underlying logic such as orm.

The application responds to the user's request.

3. Frequently asked questions

Why JWT

4. Solutions

(1) Front and rear end separation

In the previous traditional mode, the corresponding client in the background is the browser, and you can log in by using session + cookies. However, in the case of front-end separation, the back-end is only responsible for providing data through the exposed restapi, and the page rendering and routing are completed by the front-end. Because rest is stateless, there will be no session recorded to the server.

(2) Security problems caused by traditional methods

(3) Performance issues

If the authentication information is saved in the database, the back end needs to find out the user ID according to the token every time, which increases the query and storage overhead of the database

5. Coding practice

6. Expand thinking

Why not recommend using JWT for single sign on? I have introduced single sign on here?

Generally, we do not recommend using JWT for single sign on because of the renewal problem, but the renewal problem can be solved through the following solutions:

Refresh JWT per request

As long as it is about to expire, refresh JWT

Improve refreshtoken

Use redis to record the independent expiration time

Advantages of single sign on with JWT:

The session mode is used to store the user ID. at first, the user's session will only be stored on one server. For sites with multiple subdomains, each subdomain will correspond to at least one different server, for example:

www.taobao. com,nz. taobao. com,login. taobao. com

So if you want to implement in login taobao. After logging in, we can still get sessions under other subdomain names, which requires us to synchronize sessions on multiple servers

Using JWT does not have this problem, because the user's state has been transmitted to the client. Therefore, we only need to set the domain containing the JWT cookie as the top-level domain name, for example

Set-Cookie: jwt=lll. zzz. xxx; HttpOnly; max-age=980000; domain=. taobao. com

Note that the domain must be set to a dot plus top-level domain name, i.e

. taobao. com。 So, Taobao COM and * taobao. Com can accept this cookie and get JWT

7. References

https://blog.csdn.net/congyihao/article/details/70197805

https://blog.csdn.net/achenyuan/article/details/80829401

https://blog.csdn.net/qq_39691226/article/details/80570941

8. More discussion

Q1: questioner: Zhou Honghao:

Do JWT tokens need to be persisted in memcached?

A1: respondent (he Shuang):

This depends on the business requirements. If the user's information needs to be saved for a long time, it should be persistent. If it is only a short-term or even one-time user information verification, it does not need to be persistent.

Q2: questioner: Zhang Yaqiang

It seems that JWT encryption only adds DES encryption, resulting in double encryption, rather than changing the base64 encryption of JWT header

A2: respondent (he Shuang):

This really changes the encryption method of the header, replacing the base64 encryption of the header with DES encryption, because DES encryption is an encryption method that is almost impossible to be cracked at present.

Q3: questioner: Zhou Honghao

Should the server take out the userid from JWT for business query?

A3: respondent (he Shuang):

Yes, when we use JWT, we put the userid into the head of JWT, so when we need to use userid, we take it out for business requirements.

9. Acknowledgment

Thanks to Zhang Qiang, senior brother Weng Han. This tutorial is based on their previous technology sharing.

10. Conclusion

That's all for today's sharing. You are welcome to like, forward, leave messages and make bricks~

Ppt link video link

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>