Comprehensive analysis of high-level core knowledge in Java-authentication and authorization (Token authentication)

1. Advantages of Token authentication

Compared to the Sessionway authentication, using tokenfor authentication are the following three advantages:

1. Stateless

tokenItself contains all the information required for authentication, so our server does not need to store Sessioninformation, which obviously increases the availability and scalability of the system, greatly reducing the pressure on the service side. However, it is precisely because of the statelessness of the token that it also leads to its biggest shortcoming: when the backend discards a token or changes its permissions within the validity period of the token, it will not take effect immediately, and generally needs to wait until the validity period expires. In addition, when the user logs out, the token is also valid. Unless, we add additional processing logic to the backend.

2. Effectively avoid CSRF attacks

** CSRF (Cross Site Request Forgery) ** typically translated as cross-site request forgery , belonging to the field of network attacks range. Compared with security attack methods such as SQL script injection and XSS, CSRF is not as well-known as them. However, it is indeed a security hazard that every system must consider. Even the technology empire Google’s Gmail was exposed to CSRF vulnerabilities in the early years, which caused great losses to Gmail users.

So what exactly is cross-site request forgery it? Simply use your identity to send some unfriendly requests. Give a simple example:

Xiao Zhuang logged in to an online bank. He came to the post area of ​​the online bank. He saw a link below a post that said "Scientific financial management, annual profit rate exceeded 10,000". Xiao Zhuang curiously clicked on this link and found that My account is missing 10,000 yuan. Is this the case? It turns out that the hacker hid a request in the link. This request directly used Xiao Zhuang's identity to send a transfer request to the bank, that is, send a request to the bank through your Cookie.

<a src=http://www.mybank.com/Transfer?bankId=11&money=10000>
科学理财,年盈利率过万 
</>

Cause great cause of the problem is this: Sessioncertification Cookiein session_idwas sent by the browser to the server, with the help of this feature, the attacker can attack delays by allowing users to link the attack to achieve the effect.

Then why doesn't the token have such a problem?

I understand it this way: Under normal circumstances we use JWT, then, after we get a successful login token, generally choose to store in local storagethe. Then we will add this token to each request sent to the back end in some way on the front end, so that there will be no CSRF vulnerabilities. Because even if you click on an illegal link and send a request to the server, the illegal request will not carry the token, so the request will be illegal.

But this would risk XSS attack stolen, in order to avoid XSS attacks, you can choose to mark token is stored in httpOnlya cookie. However, this has caused you to provide CSRF protection yourself.

Using the above two methods which specific storage token of it, in most cases stored in the local storagecase is the best option in some cases may need to be stored in labeled httpOnlyof cookiethe better.

3. Suitable for mobile applications

If you use Session for identity authentication, you need to save a piece of information on the server side, and this method will rely on Cookie (Cookies are required to save SessionId), so it is not suitable for mobile terminals.

However, using tokens for identity authentication will not have this problem, because as long as the token can be stored by the client, it can be used, and the token can also be used across languages.

4. Single sign-on friendly

If you use Session for identity authentication, to achieve single sign-on, we need to save the user's session information on a computer, and we will also encounter the common cookie cross-domain problem. However, if the token is used for authentication, the token is stored on the client side, and these problems will not exist.

2. Token authentication common problems and solutions

1. Token is still valid in scenarios such as logout and login

Similar specific related scenarios are:

  1. sign out;
  2. change Password;
  3. The server has modified the authority or role of a user;
  4. The user's account is deleted/suspended.
  5. The user is logged off by the administrator;

This problem does not exist in the Session authentication method, because in the Session authentication method, the server can delete the corresponding Session record in this case. However, the use of token authentication is not easy to solve. We have also said that once the token is sent out, if the backend does not add other logic, it will be valid until it fails. So, how do we solve this problem? After consulting a lot of information, I summarized the following solutions:

  • Store the token in the in-memory database : Store the token in the DB. Redis in-memory database is a good choice here. If you need to invalidate a token, just delete the token from redis. However, this will lead to the step of querying whether the token exists in the DB every time a request is sent using the token, and it violates 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 make a token invalid, just add this token to the blacklist. Then, every time a token is used for a request, it will first determine whether the token exists in the blacklist.
  • Modify Secret (Secret) : We create an exclusive key for each user. If we want to invalidate a certain token, we can directly modify the key of the corresponding user. However, this is more harmful than the introduction of in-memory databases in the first two categories. For example: 1.** If the service is distributed, the keys must be synchronized on multiple machines every time a new token is issued. For this, you need to store the secret in a database or other external service, so that it is not much different from Session authentication. **2. If the user opens the system in two browsers at the same time, or also opens the system on the mobile phone, if it logs out the account from one place, it will have to log in again in other places, which is not advisable.
  • Keep the validity period of the token short and rotate frequently : a very simple way. However, it will cause the user's login status to not be persistently recorded, and users are required to log in frequently.

2. Token renewal issue

Generally, it is recommended to set the validity period of the token to be not too long. Then, how to authenticate after the token expires, and how to dynamically refresh the token so that users often need to log in again?

Let's first take a look at the general practice in session authentication: if the session is valid for 30 minutes, if the user has access within 30 minutes, the session validity is extended by 30 minutes .

  1. Similar to the practice in Session authentication : this scheme is satisfactory for most scenarios. Assuming that the token validity period given by the server is set to 30 minutes, each time the server performs verification, if it finds that the token validity period is about to expire soon, the server will regenerate the token to the client. The client checks the new and old tokens for each request, and if they are inconsistent, updates the local token. The problem with this approach is that the token will only be updated when the request is about to expire, which is not very friendly to the client.
  2. Each request returns a new token : The idea of ​​this scheme is very simple, but, obviously, the overhead will be relatively large.
  3. The token validity period is set to midnight : This solution is a compromise solution that ensures that most users can log in normally during the day and is suitable for systems that do not require high security.
  4. User login returns two tokens : the first is acessToken, whose expiration time is the expiration time of the token itself, such as half an hour, and the other is refreshToken, which has a longer expiration time, such as 1 day. After the client logs in, it saves the accessToken and refreshToken locally, and passes the accessToken to the server for each access. The server verifies the validity of the accessToken, and if it expires, it passes the refreshToken to the server. If it is valid, the server generates a new accessToken to the client. Otherwise, the client can log in again. The shortcomings of this scheme are: 1. It requires the cooperation of the client ; 2. When the user logs out, it is necessary to ensure that both tokens are invalid ; 3. There will be a temporary token unavailability in the process of re-requesting the token (you can use the the client set the timer, when accessTokenthe fast time expired, go ahead by refreshTokenacquiring new accessToken).

Three, summary

The most suitable scenario for JWT is the scenario that does not require the server to save the user state . For example, if you consider the scenario of token cancellation and token renewal , there is no particularly good solution. Most of the solutions add status to the token. It's similar to Session authentication .


Reference material: "Comprehensive Analysis of Java Intermediate and Advanced Core Knowledge" is limited to 100 copies. Some people have already obtained it through my previous article!
Seats are limited first come first served! ! ! There are more Java Pdf learning materials waiting for you! ! !
Students who want to get this learning material can click here to get it for free """""""

Guess you like

Origin blog.csdn.net/Java_Caiyo/article/details/112014326