In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to achieve the Token login verification mechanism". In the daily operation, I believe many people have doubts about how to achieve the Token login verification mechanism. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to achieve the Token login verification mechanism". Next, please follow the editor to study!
Introduction to session
Programmers who have done Web development should be familiar with Session, which is a piece of memory stored on the server side and is generally used to store the user's session information.
After the user has successfully logged in through the user name and password, the server-side program will open up a piece of Session memory space on the server side and store the user's information in this space, and the server will write a value of Session_id in cookie, which is used to identify the memory space.
The next time the user visits, he will bring the session_id in the cookie, and the server will take the id to find the corresponding session. If the user's login information is already available in the session, the user has already logged in.
Using Session to maintain session information is very simple to use, and the technology is very mature. But there are also the following problems:
Server pressure: usually Session is stored in memory, each user after authentication will save session data in the memory of the server, and when the number of users increases, the pressure on the server increases.
Session sharing: nowadays, many applications are distributed clusters, so we need to do additional operations for Session sharing.
CSRF cross-site forgery request attack: the Session mechanism is based on cookie on the browser side. If cookie is intercepted, users will be vulnerable to cross-site request forgery attacks.
Authentication based on token
The authentication mechanism based on token returns the authentication information to the client and stores it. The next time you visit another page, you need to pass the authentication information back to the server from the client. The simple process is as follows:
The client requests login with a user name and password
The server receives a request to verify the user name and password
After the verification is successful, the server will issue a Token and send the Token to the client
After receiving the Token, the client can store it, such as in Cookie or Local Storage
Each time the client requests resources from the server, it needs to bring the Token signed by the server.
The server receives the request, and then verifies the Token in the client request. If the verification is successful, it returns the requested data to the client.
The authentication mechanism based on token has the following advantages:
Cross-domain access is supported and token is placed in the request header, while cookie does not support cross-domain access
Stateless, the server does not need to store the token, it only needs to verify whether the token information is correct, while the session needs to be stored on the server, usually through the sessionID in the cookie to find the corresponding session on the server.
There is no need to bind to a special authentication scheme (traditional username and password login), as long as the generated token is in line with our expected settings.
It is more suitable for mobile (Android,iOS, Mini Program, etc.). Native platforms like this do not support cookie. For example, WeChat Mini Programs, each request is a session. Of course, we can manually add cookie for him each time. For more information, please see another blog post of the blogger.
Avoid CSRF cross-site forgery attacks, or because you do not rely on cookie
One disadvantage is that it is slightly more complex to implement than the traditional session login mechanism, and another big disadvantage is that because the server does not save token, it is impossible to abolish a certain token or change the permissions of token in the process of use. That is, once the token is signed, it will remain valid until it expires, unless the server deploys additional logic.
Log out and log in, as long as the front end clears the token information.
Implementation of token Authentication based on JWT
JWT (JSON Web Token) is the representative of token-based authentication. Here, we use JWT as a column to introduce the token-based authentication mechanism.
Need to introduce JWT dependencies
Com.auth0 java-jwt 3.8.2
The utility classes for generating token and verifying token are as follows:
Public class JWTTokenUtil {/ / set expiration time private static final long EXPIRE_DATE=30*60*100000; / / token key private static final String TOKEN_SECRET = "ZCfasfhuaUUHufguGuwu2020BQWE"; public static String token (String username,String password) {String token = ""; try {/ / expiration time Date date = new Date (System.currentTimeMillis () + EXPIRE_DATE) / / key and encryption algorithm Algorithm algorithm = Algorithm.HMAC256 (TOKEN_SECRET); / / set header information Map header = new HashMap (); header.put ("typ", "JWT"); header.put ("alg", "HS256") / / generate signature token = JWT.create () .withheader (header) .withClaim ("username", username) .withClaim ("password", password) .withExpiresAt (date) .sign (algorithm);} catch (Exception e) {e.printStackTrace () Return null;} return token;} public static boolean verify (String token) {/ * @ desc verify token by returning true * @ params [token] string * * / try {Algorithm algorithm = Algorithm.HMAC256 (TOKEN_SECRET); JWTVerifier verifier = JWT.require (algorithm). Build () DecodedJWT jwt = verifier.verify (token); return true;} catch (Exception e) {e.printStackTrace (); return false;}} public static void main (String [] args) {String username = "name1"; String password = "pw1" / / Note: generally, private information such as passwords are not put in payload. Here is just an example: String token = token (username,password); System.out.println (token); boolean b = verify (token); System.out.println (b);}}
The implementation results are as follows:
Connected to the target VM, address: '127.0.0.1 transport:' socket'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTU5NzM5Nzc0OCwidXNlcm5hbWUiOiJ6aGFuZ3NhbiJ9.LI5S_nX-YcqtExI9UtKiP8FPqpQW_ccaws2coLzyOS0true
With regard to the DecodedJWT class, you can focus on it, which contains user information after decoding.
Instructions for using JWT
The client receives the JWT returned by the server, which can be stored in Cookie or localStorage.
Since then, the client will bring this JWT with it every time it communicates with the server. You can send it automatically in Cookie, but it's not cross-domain, so it's better to put it in the header Authorization field of the HTTP request.
Authorization: Bearer
Alternatively, when crossing domains, the JWT is placed in the data body of the POST request.
JWT itself contains authentication information, and once disclosed, anyone can get all the privileges 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.
In order to reduce embezzlement, JWT should not use the HTTP protocol for plain code transmission, but should use the HTTPS protocol for transmission. (or encrypt the JWT between the front and back ends before transmitting)
A question about JWT
The key point in the process of generating JWT token above is the key. If the key is leaked, is it possible to forge the token?
There is the key value of the production environment, the development of programmers is likely to know, how to prevent the program from stealing, forged token value? I hope the experienced boss will give me some advice.
/ / token key private static final String TOKEN_SECRET = "ZCfasfhuaUUHufguGuwu2020BQWE"
With regard to the above questions, give a simple and easy-to-understand solution.
There is another way to use jwt to generate token. When a user logs in, the SecretKey that generates token is a random number, that is, each user, each time he logs in, the jwt SecretKey is random and saved to the cache. Key is the login account (of course, if distributed cache is used, Redis,sqlserver cache is used, etc.). In short, the client access interface is that header should bring the login account and token, and the server will get the login account. Go to the cache to get the corresponding SecretKey, and then check the token. Anti-counterfeiting token (this scheme can prevent counterfeiting to some extent, but can not prevent token leaks from being hijacked).
At this point, the study on "how to implement the Token login verification mechanism" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.