In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to use JWT in SpringBootSecurity. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
JWT usage
Earlier, we briefly introduced the method of changing the default page login to the front-end separate interface asynchronous login, which can help us to achieve the basic front-end separate login function. But this basic login has one thing in common with the previous page login, that is, it uses session and cookie to maintain the login state. The problem with this approach is that it is not scalable. Of course, there is no problem with a stand-alone machine. If it is a server cluster or a cross-domain service-oriented architecture, session data sharing is required, and each server can read session.
One solution is to persist session data and write to redis or other persistence layers. After receiving the request, the various services request data from the persistence layer. The advantage of this scheme is that the structure is clear, and the disadvantage is that the engineering quantity is relatively large. In addition, if the persistence layer fails, it will fail at a single point.
Another solution is that the server simply does not save the session data, all the data is saved on the client, and each request is sent back to the server. JWT is a representative of this kind of scheme. On the theoretical knowledge of JWT, it is recommended to refer to the tutorial written by Ruan Yifeng: the introduction to JSON Web Token, which I think is probably the clearest one, and the following implementation of jwt is also based on this tutorial.
For specific theoretical knowledge, you can refer to the tutorial. Here is a simple description of the process. After a user logs in successfully, a token information is returned in header, which contains encrypted user information, digital signature and, most importantly, expiration time. After receiving it, the client will carry this token in every access interface header. After successful verification on the server, it means that the user is logged in, and then it can be obtained from the user again after expiration.
The specific token content includes three blocks: the header (encrypted information), the carrier (user information) and the signature (in front of the two parts of the signature). The three blocks are connected by an English full stop (i.e. ".") to form a complete token information.
Process design
Based on the previous theory, let's design how to use jwt. First of all, we use jwt, so we can stop using session and cookie, so the first step is:
Configure session to be stateless in the security configuration file.
Then consider building the jwt message body, which has three parts, the first part is the header, and the content is the encryption type:
In the above code, the alg attribute represents the signature algorithm (algorithm), and the default is HMAC SHA256 (written as HS256); the typ attribute indicates the token type (type), and the JWT token is written as JWT. Finally, the above JSON object is converted into a string using the Base64URL algorithm as the first part. So the second step is:
Configure session to be stateless in the security configuration file.
Determine the format of header information
The next step is to determine the second part, the message carrier (Payload), which is also a json object that holds the data that actually needs to be passed. JWT specifies seven official fields to choose from:
Of course, in addition to these, you can also add some other content, such as user information, and this JSON object also needs to be converted into a string using the Base64URL algorithm, so the third and fourth steps are:
Configure session to be stateless in the security configuration file.
Determine the format of header information
Determine the body of the message
Use HMAC SHA256 algorithm to sign header and message body as the third part
Now that the basic combination of token messages is complete, both the user login success and the client access interface need to put token in the header, whose name is Authorization. Therefore, the final step is to verify the validity of token when the client accesses non-login and other interfaces normally. Therefore, the overall design process is as follows:
Configure session to be stateless in the security configuration file.
Determine the format of header information
Determine the body of the message
Use HMAC SHA256 algorithm to sign header and message body as the third part
Add a filter to verify the legitimacy of token
Modify configuration class
The above process is finished. Let's modify the project according to the process. First, modify the security configuration class:
After the configuration, start the project, access the login, and you can see that no cookie has been saved after the login is successful.
Define JWT utility classes
First, let's define several constants:
Then define the Base64URL algorithm encoding and decoding methods:
Then define the HmacSHA256 encryption algorithm and the method to obtain the signature:
Finally, design a simple method to verify token:
In this way, the jwt utility class is designed, and at present these methods are sufficient to manipulate token content.
Define JWT message object
The following is to define the content of jwt. In fact, the content is very simple, only three parts. Therefore, you can define three fields:
Let's take a look at the construction method.
This construction method is very convenient. After using it to create an object, the three parts of jwt are basically completed, the header part and payload part are all encoded, and the signature is completed, so the following rewrite toString method can generate token directly:
As you can see here, token as a whole is not encrypted by default, but it can also be encrypted. After the original Token is generated, it can be encrypted again with the key. So don't put important information such as passwords in token.
Modify login success processor
After the user logs in successfully, the session is no longer sent to the user, but the jwt is sent to the user, so the processor for modifying the login success is as follows:
Notice that the user's password information is manually set to null above. Here, for convenience, use fastjson to combine objects directly.
Modify entity class
When you take the token access interface, you need to switch the token back to the login user object, so our user entity class is the same as the field name in token. Let's modify it. Let's first look at the role entity class:
Take a look at the user entity class:
As you can see, the basic principle is that the modified name is the same as the necessary field name of the parent class, which is also the recommended field name.
Write token validation filter
After we change the session of security to stateless, although the session is no longer passed, the filter of security does not fail, so the effect is that after the login is successful, the access interface shows that it is not logged in. Now when we use token, we need to add a filter to verify the token before logging in, and put the information directly into the SecurityContextHolder after verification. In this way, each login depends on verifying token to determine whether to log in or not, instead of relying on session. Take a look at this filter:
This filter is very simple, inherits the GenericFilterBean class, directly gets token, determines that token is not empty, verifies token, and takes user information from the payload of token and puts it into SecurityContextHolder. Token error is returned directly if verification fails or token expires. The logic is simple.
Finally, in the security class, configure the filter to the front:
This completes our custom jwt process. You can test it in postman, starting with logging in:
After logging in successfully, you can see the information of token in header, and then use token to put it into the header of another interface to access the interface. You can see that the access is successful:
If you are interested, you can follow up the process with debug.
Several characteristics of JWT
(1) JWT is not encrypted by default, but it can also be encrypted. After the original Token is generated, it can be encrypted again with the key.
(2) if JWT is not encrypted, secret data cannot be written to JWT.
(3) JWT can be used not only for authentication, but also for exchanging information. Effective use of JWT can reduce the number of times the server queries the database.
(4) the biggest disadvantage of JWT is that because the server does not save the session state, it cannot abolish a token or change the permissions of token during use. That is, once the JWT is signed, it will remain valid until it expires, unless the server deploys additional logic.
(5) JWT itself contains authentication information, and once disclosed, anyone can get all the permissions of the token. To reduce embezzlement, the validity period of JWT should be set to be short. For some of the more important permissions, users should be authenticated again when using them.
(6) in order to reduce embezzlement, JWT should not use HTTP protocol for clear code transmission, but should use HTTPS protocol for transmission.
The above is how to use JWT in SpringBootSecurity. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.