In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how SpringBoot2 integrates the JWT framework to solve the problem of Token cross-domain verification, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's learn about it together.
First, traditional Session authentication 1, authentication process 1, the user sends the user name and password to the server. 2. Save the relevant data in the current conversation (session) after verification by the server. 3. The server returns sessionId to and writes to the client Cookie. 4. Every time the client requests, it needs to send the sessionId back to the server through Cookie. 5. The server receives the sessionId and verifies the client. 2. Existing problems: 1. The session is stored on the server, and when the client accesses with high concurrency, the server is under great pressure. 2. Poor scalability and server cluster require session data sharing. II. Brief introduction of JWT
JWT (full name: JSON Web Token), in the process of HTTP-based communication, identity authentication.
1. Authentication process 1, the client logs in to the server through the user name and password; 2, the server verifies the client's identity; 3, after the server authenticates, it generates a JSON object and sends it back to the client; 4. When the client communicates with the server, it sends back the JSON object; 5. The server parses the JSON object to obtain the user's identity 6. The server does not need to store the JSON (Token) object, and the identity information can be parsed. 2. JWT structure description
Grab a live Token.
{"msg": "successful verification", "code": 200,200 "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9. EyJzdWIiOiJhZG1pbiIsImlhdCI6iZEIj3fQ. UEJSJagJf1j7A55Wwr1bGsB5YQoAyz5rbFtF"}
The above Token is manually formatted and is actually formatted with "." A complete long string delimited.
JWT structure
1, header (header) declaration type and encryption algorithm; 2, load (payload) carries some user identity information; 3, signature (signature) signature information. 3. How to use JWT
It is usually recommended that the client put the header information Authorization field of the HTTP request.
Authorization: Bearer
Server acquires JWT mode
String token = request.getHeader ("token") 3. Integrate with SpringBoot2 1, core dependency file io.jsonwebtoken jjwt 0.7.02, configuration file server: port: 7009spring: application: name: ware-jwt-tokenconfig: jwt: # encryption key secret: iwqjhda8232bjgh532 [cicada-smile] # token valid duration expire: 3600 # header name header: token3, JWT configuration code block @ ConfigurationProperties (prefix = "config.jwt") @ Componentpublic class JwtConfig {/ * * identified by identity ID Generate Token * / public String getToken (String identityId) {Date nowDate = new Date () / / expiration time Date expireDate = new Date (nowDate.getTime () + expire * 1000); return Jwts.builder () .setHeaderParam ("typ", "JWT") .setSubject (identityId) .setIssuedAt (nowDate) .setExpiration (expireDate) .signWith (SignatureAlgorithm.HS512, secret) .compact () } / * * get registration information in Token * / public Claims getTokenClaim (String token) {try {return Jwts.parser (). SetSigningKey (secret) .parseClaimsJws (token). GetBody ();} catch (Exception e) {e.printStackTrace (); return null }} / * * Token expiration verification * / public boolean isTokenExpired (Date expirationTime) {return expirationTime.before (new Date ());} private String secret; private long expire; private String header; / / omit GET and SET} IV. Token intercept case 1, configure Token interceptor @ Componentpublic class TokenInterceptor extends HandlerInterceptorAdapter {@ Resource private JwtConfig jwtConfig @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / address filtering String uri = request.getRequestURI (); if (uri.contains ("/ login")) {return true;} / / Token verify String token = request.getHeader (jwtConfig.getHeader ()) If (StringUtils.isEmpty (token)) {token = request.getParameter (jwtConfig.getHeader ());} if (StringUtils.isEmpty (token)) {throw new Exception (jwtConfig.getHeader () + "cannot be empty");} Claims claims = jwtConfig.getTokenClaim (token) If (claims = = null | | jwtConfig.isTokenExpired (claims.getExpiration () {throw new Exception (jwtConfig.getHeader () + "invalid, please log in again");} / / set identityId user identity ID request.setAttribute ("identityId", claims.getSubject ()); return true;}} 2, interceptor registration @ Configurationpublic class WebConfig implements WebMvcConfigurer {@ Resource private TokenInterceptor tokenInterceptor Public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (tokenInterceptor) .addPathPatterns ("/ * *");}} 3, test interface code @ RestControllerpublic class TokenController {@ Resource private JwtConfig jwtConfig / / the interceptor is directly released, returning Token @ PostMapping ("/ login") public Map login (@ RequestParam ("userName") String userName, @ RequestParam ("passWord") String passWord) {Map result = new HashMap (); / / omitting the data source check String token = jwtConfig.getToken (userName+passWord) If (! StringUtils.isEmpty (token)) {result.put ("token", token);} result.put ("userName", userName); return result;} / / Interface that requires Token authentication @ PostMapping ("/ info") public String info () {return "info" }} these are all the contents of the article "how SpringBoot2 integrates the JWT framework to solve the problem of Token cross-domain verification". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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.