Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate JWT into Spring Boot to realize Front and back end Authentication

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

In this article, the editor introduces in detail "how Spring Boot integrates JWT to achieve front and back-end authentication". The content is detailed, the steps are clear, and the details are handled properly. I hope this "Spring Boot how to integrate JWT to achieve front-and back-end authentication" article can help you solve your doubts.

Introduction to JWT

JWT (full name: Json Web Token) is an open standard (RFC 7519) that defines a compact, self-contained way to securely transfer information between parties as JSON objects.

Why do you want to use JWT traditional session authentication what are the disadvantages?

The login information of each user is saved to the Session of the server, and as the number of users increases, the server overhead increases significantly.

The information of Session is stored in the memory of the server, which will lead to failure for distributed applications. Although the information of session can be stored in the cache of Redis, it may increase the complexity.

Because Session authentication is based on Cookie, it is not suitable for non-browser and mobile phone.

In the front and back end separation system, because there is cross-domain in the front and rear end, and the Cookie information can not be crossed, it is impossible to continue cross-domain authentication by using Session authentication.

Advantages of JWT certification

Simplicity: JWT Token has a small amount of data and fast transmission speed.

Cross-language: JWT Token is stored on the client in JSON encrypted form, so JWT is cross-language and is supported in any web form. Cross-platform: does not rely on cookie and session, does not need to store session information on the server, is very suitable for distributed applications, applications for expansion.

Data structure of JWT

Header

The first part of JWT is the header, which is a Json object that describes JWT metadata, usually as shown below.

{"alg": "HS256", "typ": "JWT"}

The alg attribute represents the algorithm used by the signature, which defaults to HMAC SHA256 (written as HS256), the typ attribute indicates the type of token, and the JWT token is written as JWT.

Payload

The second part of the JWT is Payload, which is also a Json object, with seven default fields to choose from in addition to the data that needs to be passed. Iss: publisher exp: expiration time sub: subject aud: user nbf: not available before that iat: release time jti:JWT ID is used to identify the JWT

{/ / default fields "sub": "subject 123", / / Custom fields "name": "java", "isAdmin": "true", "loginTime": "2021-12-05 12:00:03"}

It should be noted that JWT is unencrypted by default, and anyone can interpret its content, so if some sensitive information is not stored here, in case the information is leaked. The JSON object is also converted to a string save using the Base64 URL algorithm.

Signature

The signature hash part signs the above two parts of data. You need to use base64-encoded header and payload data to generate hashes through the specified algorithm to ensure that the data will not be tampered with.

Spring Boot Integration JWT introduces Jwt package io.jsonwebtoken jjwt 0.9.1 to write jwt utility class public class JwtUtil {/ / create jwtpublic static String createJWT (String subject, String issue, Object claim, long ttlMillis) {/ / current time long nowMillis = System.currentTimeMillis (); / / Expiration time long expireMillis = nowMillis + ttlMillis String result = Jwts.builder () .setSubject (subject) / / set theme .setIssuer (issue) / / publisher .setId (issue) / / jwtID .setExpiration (new Date (expireMillis)) / / set expiration date .claim ("user", claim) / / subject Can contain user information .signWith (getSignatureAlgorithm (), getSignedKey ()) / / encryption algorithm .signsWith (CompressionCodecs.DEFLATE) .signWith (compact ()) / / A pair of load compression return result;} / / parsing jwt public static Jws pareseJWT (String jwt) {Jws claims; try {claims = Jwts.parser (). SetSigningKey (getSignedKey ()) .parseClaimsJws (jwt);} catch (Exception ex) {claims = null } return claims;} / / get topic information public static Claims getClaims (String jwt) {Claims claims; try {claims = Jwts.parser (). SetSigningKey (getSignedKey ()) .parseClaimsJws (jwt). GetBody ();} catch (Exception ex) {claims = null } return claims;}} / * get the key * * @ return Key * / private static Key getSignedKey () {byte [] apiKeySecretBytes = DatatypeConverter .parseBase64Binary (getAuthKey ()); Key signingKey = new SecretKeySpec (apiKeySecretBytes, getSignatureAlgorithm (). GetJcaName ()); return signingKey } private static SignatureAlgorithm getSignatureAlgorithm () {return SignatureAlgorithm.HS256;} / / to obtain the key, you can configure public static String getAuthKey () {String auth = "123 authentication interceptor Componentpublic class TokenInterceptor extends HandlerInterceptorAdapter {public static Log logger = LogManager.getLogger (TokenInterceptor.class)" dynamically. @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String uri = request.getRequestURI (); logger.info ("start TokenInterceptor preHandle.." + uri); / / need to filter the special request if (SystemUtil.isFree (uri) | | SystemUtil.isProtected (uri)) {return true } String metohd=request.getMethod (). ToString (); logger.info ("TokenInterceptor request method:" + metohd); / / the options method needs to filter if ("OPTIONS" .equals (metohd)) {return true;} / / whether to enable token authentication boolean flag = SystemUtil.getVerifyToken () ResponseResult result = new ResponseResult (); / / get token String token= request.getHeader ("X-Token") from the requested head information; if (flag) {if (StringUtils.isEmpty (token)) {token=request.getParameter ("X-Token") } / / if (StringUtils.isEmpty (token)) {result.setCode (ResultCode.NEED_AUTH.getCode ()); result.setMsg (ResultCode.NEED_AUTH.getMsg ()); WebUtil.writeJson (result, response); return false does not exist in token } else {Claims claims = JwtUtil.getClaims (token); String subject = ""; if (claims! = null) {subject = claims.getSubject () / / verify the topic if (StringUtils.isEmpty (subject)) {result.setCode (ResultCode.INVALID_TOKEN.getCode ()); result.setMsg (ResultCode.INVALID_TOKEN.getMsg ()); WebUtil.writeJson (result, response) Return false;}} else {result.setCode (ResultCode.INVALID_TOKEN.getCode ()) Result.setMsg (ResultCode.INVALID_TOKEN.getMsg ()); WebUtil.writeJson (result, response); return false;} return true;}} configure interceptor @ Configurationpublic class WebConfig implements WebMvcConfigurer {@ Resource private TokenInterceptor tokenInterceptor Public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (tokenInterceptor) .addPathPatterns ("/ * *");} login verification process

Sample code @ RequestMapping ("login") public Result login (HttpServletResponse response) {Map map = new HashMap (); / / Result result = loginAuth (user); int code = result.getCode (); / / login authentication success if (code = = ResultCode.SUCCESS) {/ / defaults to 7 days Long ttlMillis = 7 million * 60 * 60 * 24 / / expiration time long expreTime = System.currentTimeMillis () + ttlMillis; String tokenKey = UUID.randomUUID (). ToString (); String tokenId = JwtUtil.createJWT (user.getUserId (), tokenKey, user.getPassword (), expreTime); map.put ("expreTime", expreTime); map.put ("tokenId", tokenId) } else {logger.error ("login error:" + FastJsonUtil.toJSONString (result));} return result } after reading this, the article "how to integrate Spring Boot with JWT to achieve front-end authentication" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to learn more about related articles, please 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report