A brief analysis of JWT

Cookie-session

We all know that JWT is generally used for user login and other operations that need to be remembered. Before talking about JWT, we have to talk about the previous cookie-session login. Because the http protocol is a stateless protocol, that is, every time the server receives a request from the client, it is a brand new request. The server does not know the client’s historical request records (that is, even if you refresh it after logging in) I don’t recognize you anymore and want you to continue logging in); the main purpose of Session and Cookie is to make up for the stateless nature of HTTP.

Internet services are inseparable from user authentication. The general process is as follows:

 This is the Cookie-session method 

What is Session


The client requests the server, and the server will open an area for this request 内存空间. This object is the Session object, and the storage structure is ConcurrentHashMap. Session makes up for the stateless nature of HTTP. The server can use Session to store some operation records of the client during the same session. As shown in the figure above, we will store session_id in this process.

Disadvantages of cookie-session mechanism

Scaling is not good


Of course, there is no problem with a single machine. If it is a server cluster or a cross-domain service-oriented architecture, session data sharing is required, and each server can read the session. For example, server A stores the session. After load balancing, if the number of visits to A increases sharply within a period of time, it will be forwarded to B for access. However, server B does not store A's session, which will cause the session to become invalid. One solution is to persist session data and write it to the database or other persistence layer. After receiving the request, various services request data from the persistence layer. The advantage of this solution is that the structure is clear, but the disadvantage is that the amount of engineering is relatively large (the session is stored on the server side, which increases the server overhead. When there are many users, the server performance will be greatly reduced). In addition, if the persistence layer fails, it will be a single point of failure.

Another solution is that the server simply does not save the session data. All data is saved on the client (a very important idea, let the client help us store or do calculations to reduce the pressure on the server), and each request is sent back to the server. . JWT is a representative of this solution.

Poor security:

Cookie security is a big issue because they are stored in clear text, which can pose a security risk because anyone can open and tamper with cookies. The ease with which cookies are discovered on the client side means they can be easily hacked and modified. It is equivalent to legally logging into your account.

Can see cookies directly

JWT

How JWT works

After server authentication, a JSON object is generated and sent back to the user, as shown below.

In the future, when the user communicates with the server, this JSON object will be sent back. The server relies solely on this object to identify the user. In order to prevent users from tampering with data, the server will add a signature when generating this object. The server does not save any session data. In other words, the server becomes stateless, making it easier to expand.

JWT data structure

The actual JWT looks like this

We can  parse JWT through JSON Web Tokens - jwt.io

It is a long string .separated into three parts by dots ( ). Note that there is no line break inside the JWT. It is written in several lines just for the convenience of display.

The three parts of the JWT are as follows.

Written in one line, it looks like the following.

 The Header part is a JSON object describing the metadata of the JWT

The payload part is also a json object, used to store the actual data that needs to be transferred. JWT specifies 7 official fields for selection.

 In addition to official fields, you can also define private fields in this section. Here is an example.

Note that JWT is not encrypted by default and can be read by anyone, so do not put secret information in this section.

The Signature part is a signature of the first two parts to prevent data tampering.

How to use JWT

The client receives the JWT returned by the server, which can be stored in a cookie or in localStorage.

After that, every time the client communicates with the server, it must bring this JWT. You can put it in a cookie and send it automatically, but this cannot cross domains, so a better approach is to put it in the header Authorizationfield of the HTTP request.

 Another approach is to put the JWT in the data body of the POST request when crossing domains.

Features of JWT

For the third point:

That is to say, a user logs in to mobile phone A, and then logs in to mobile phone B. Before expiration, both mobile phones A and B can log in. It is impossible to let A expire after B logs in. If you want to do this, you must Let the server maintain a list (record whether the account has been issued a token), so it returns to the old way of session.

After talking about JWT, you may still have doubts. Isn't this similar to cookie-session? Cookie-session returns session_id, and JWT returns token. Then your cookie may be intercepted and modified, but your token will not be?

In fact, JWT can prevent token tampering through the Signature field. Use private key encryption to generate token and public key decryption to obtain the information in the token, so if the Signature of JWT is cracked, it will be GG (for example, some developers directly copy the JWT examples from the Internet without modification, which can easily be cracked by brute force) )

On the other hand, security detection can also be done using https or code level. For example, if the IP address changes, the MAC address changes, etc., you can ask to log in again.

Since the token cannot be set to be invalid after it is generated, the only way to generate a new refresh_token is to set the token expiration time. And HTTPS protocol should be used for transmission (these are the contents of feature 6 in the above figure)

Besides security, are there any benefits to JWT?

The official explanation given by JWT is (compare SWT and SAML):

JWT is lightweight because it uses JSON: Since JSON is not as verbose as XML, when encoded, its size is also smaller, making JWT more compact than SAML. This makes JWT a good choice for delivery in HTML and HTTP environments.

Security: SWT can only be signed symmetrically by a shared key using the HMAC algorithm. However, JWT and SAML tokens can be signed using public/private key pairs in the form of X.509 certificates. Compared to the simplicity of signing JSON, it is very difficult to sign XML using XML digital signatures without introducing obscure security holes.

JSON can be easily parsed in various languages: JSON parsers are common in most programming languages ​​because they map directly to objects. In contrast, XML has no natural document-to-object mapping. This makes using JWT easier than using SAML assertions.

Cross-platform: JWT is used at Internet scale. This highlights the ease of client-side handling of JSON Web Tokens on multiple platforms, especially mobile platforms.

Advantages of JWT:

  • JWTIs a stateless authentication mechanism because user state is never saved in the database. Because the JWT is self-contained, all the necessary information is there, reducing the need to go back and forth to the database. Using JWT we don't need to query the database to authenticate the user for every api call
  • Security, use signature and expiration time (refresh_token) to prevent CSRF(cross-site request forgery vulnerability) attacks.
  • JWT is compact. Due to its size, it can be sent via URL, POST parameters or in HTTP headers
  • Cross-domain, cookies are bound to a single domain. Cookies created on a domain cannot be read across domains, whereas you can send the token to any domain you like

Disadvantages of JWT:

  • It is not absolutely safe. If the Signature is cracked (although it is not that simple), hackers can change the payload at will to upgrade ordinary users to administrators and destroy the system, etc.
  • Compared to cookie-session, which is available out of the box, JWT requires you to write additional code yourself.

Best practices for JWT:

  • Always set an expiration date for any token you issue
  • Avoid sending tokens in URL parameters whenever possible
  • Include an (Audience) statement (or similar statement) to specify the intended recipients of the token. This prevents it from being used on different websites
  • Enable the issuing server to revoke the token (for example, on logout)

Reference:
Session-based identity theft - Tencent Cloud Developer Community - Tencent Cloud (tencent.com)

JSON Web Token introductory tutorial - Ruan Yifeng's web log (ruanyifeng.com)

JSON Web Token Introduction - jwt.io

learn-json-web-tokens/README.md at master · dwyl/learn-json-web-tokens (github.com)
JWT attacks | Web Security Academy (portswigger.net)
JSON Web Tokens (JWT) Cookie-relative Advantages/Disadvantages - Stack Overflow (stackoverflow.com)
 

Guess you like

Origin blog.csdn.net/qq_55621259/article/details/128405972