Spring Security With JWT (JWT, JWT, JWT, JWT) The Demo was very simple and did not cover some of the problems with JWT. Therefore, a separate article was selected to introduce. In order to complete this article, I have consulted a lot of materials and literature, which I think should be helpful to you.

Related reading:

  • “Ask take you distinguish Authentication, Authorization, and cookies, Session, Token”
  • For beginners to start Spring Security With JWT Demo
  • Spring Boot uses JWT for identity and permission authentication

Advantages of Token authentication

Compared with Session authentication, token authentication has the following advantages:

1. A stateless

Token itself contains all the information needed for authentication, so our server does not need to store Session information, which obviously increases the availability and scalability of the system and greatly reduces the pressure on the server side. However, it is the statelessness of the token that leads to its biggest disadvantage: when the backend discards a token or changes its permissions during the token validity period, it does not take effect immediately. It usually has to wait until after the token validity period. In addition, the token is still valid when the user Logout is logged out. Unless, of course, we add some extra processing logic on the back end.

2. CSRF attacks are effectively avoided

**CSRF (Cross Site Request Forgery) ** is generally translated as cross-site Request Forgery, which belongs to the domain of network attack. CSRF is not as well known as SQL script injection, XSS, and other security attacks. However, it is indeed a security concern for every system, and even the technology empire Google’s Gmail was exposed to have a CSRF vulnerability earlier this year, which caused great losses to Gmail users.

So what exactly is cross-site request forgery? Simply use your identity to send unfriendly requests. Here’s a simple example:

Small strong login to an online bank, he came to the online bank’s post area, see a post below a link written “scientific financial management, annual profit rate of more than 10,000”, small strong curious click on the link, the result found his account less 10,000 yuan. How could this be? It turns out that the hacker hid a request in the link, which directly used Xiao Zhuang’s identity to send a transfer request to the bank, that is, through your Cookie to send a request to the bank.

<a src="http://www.mybank.com/Transfer?bankId=11&money=10000">Scientific financial management, annual profit rate of more than 10,000</a>
Copy the code

The reason for this problem is that the session_ID in the Cookie of Session authentication is sent to the server by the browser. With this feature, the attacker can make the user click the link to attack, so as to achieve the attack effect.

So why don’t tokens have this problem?

In general, when we use JWT, we will choose to store the token in local storage after logging in successfully. We then add this token to each request sent to the back end in some way on the front end so that CSRF vulnerabilities do not occur. Because, even if one of you clicked the illegal link and sent the request to the server, the illegal request would not carry the token, so the request would be illegal.

However, there is a risk of theft in an XSS attack. To avoid an XSS attack, you can choose to store the token in a cookie marked httpOnly. However, this results in you having to provide CSRF protection yourself.

In most cases, local storage is the best choice. In some cases, it may be better to store tokens in cookies marked httpOnly.

3. Suitable for mobile applications

Session authentication requires saving information on the server, and this method relies on cookies (requiring cookies to store the SessionId), so it is not suitable for mobile devices.

However, authentication with tokens does not have this problem because tokens can be used as long as they can be stored by clients and can be used across languages.

4. Single sign-on friendly

If Session is used for identity authentication and single sign-on is realized, we need to save the user’s Session information on a computer, and also encounter the common cross-domain problem of cookies. However, with token authentication, the token is stored in the client and does not have these problems.

Faqs about Token authentication and their solutions

1. The token is valid in scenarios such as logout and login

Similar specific related scenarios are:

  1. Log out;
  2. Change the password.
  3. The server modifies the permission or role of a user.
  4. The user’s account has been deleted or suspended.
  5. The user is logged out by the administrator.

This problem does not exist in Session authentication, because in this case, the server can delete the corresponding Session record. However, using token authentication is not easy to solve. As we have said, once the token is dispatched, it remains valid until it expires if no additional logic is added to the back end. So how do we solve this problem? After consulting a lot of information, the following schemes are summarized:

  • Store tokens in an in-memory database: Store tokens in a DB, redis in-memory database is a good choice here. If you need to invalidate a token, simply delete it from Redis. However, this would result in checking the DB for the presence of the token every time a request is sent using the token, and would violate the STATeless principle of JWT.
  • Blacklist mechanism: Similar to the above method, use an in-memory database such as Redis to maintain a blacklist. If you want to invalidate a token, add it to the blacklist directly. Then, each time a request is made using a token, it will determine whether the token is in the blacklist.
  • Modify Secret: We create a private key for each user. If we want to invalidate a token, we can simply modify the corresponding user’s key. However, compared with the first two methods, the introduction of in-memory database brings more harm, such as: ① If the service is distributed, each time a new token is issued, the key must be synchronized across multiple machines. To do this, you will need to store secrets in a database or other external service, which is not too different from Session authentication. ② If the user opens the system in two browsers at the same time, or also opens the system in the mobile terminal, if it exits the account from one place, then it has to re-log in in other places, which is not desirable.
  • Keep the duration of the token short and rotate frequently: an easy way to do it. However, the user login status will not be recorded continuously and the user must log in frequently.

To solve the problem that the token is still valid after the password is changed, it is relatively easy. I think a better way is to sign the token with the hash value of the user’s password. Therefore, if the password changes, any previous token will automatically not be validated.

2. Token renewal problem

It is recommended that the validity period of a token is not long. How do I authenticate the token after it expires and dynamically refresh the token to avoid frequent login?

Let’s take a look at the common practice in Session authentication: if a Session is valid for 30 minutes, if the user accesses the Session within 30 minutes, the Session validity is extended by 30 minutes.

  1. Similar to what is done in Session authentication: this scheme satisfies most scenarios. Assume that the validity period of the token provided by the server is set to 30 minutes. If the validity period of the token is about to expire during each verification, the server generates the token to the client again. The client checks the old and new tokens on each request and updates the local token if they are inconsistent. The problem with this approach is that the request only updates the token when it is about to expire, which is not very client-friendly.
  2. Return a new token on every request: The idea is simple, but obviously expensive.
  3. The token validity period is set to midnight. This solution is a compromise solution that ensures that most users can log in during the day and is suitable for systems that do not require high security requirements.
  4. The user login returns two tokens: the first one is acessToken, which has an expiration time such as half an hour, and the other one is refreshToken which has a longer expiration time such as 1 day. After logging in, the client saves accessToken and refreshToken locally and passes accessToken to the server on each access. The server validates accessToken and passes refreshToken to the server if it expires. If valid, the server generates a new accessToken to the client. Otherwise, the client can log in again. The disadvantages of this scheme are: ① ️ needs the client to cooperate; ② ️ users should ensure that both tokens are invalid when logging out; ③ In the process of re-requesting to obtain the token, the token may be temporarily unavailable (timer can be set on the client to obtain new accessToken through refreshToken when accessToken is about to expire).

conclusion

JWT is most suitable for scenarios that do not require the server to store the user state. For example, there is no good solution when considering token deregistration and token renewal. Most solutions add state to tokens, which is similar to Session authentication.

Reference

  • JWT hyperdetailed analysis
  • Medium.com/devgorilla/…
  • medium.com/@agungsanto…
  • Invalidating JSON Web Tokens

By Snailclimb: JWT identity pros and cons and FAQ solutions source: Github