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 use JWT to generate Token for Interface Authentication in Java

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

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use JWT to generate Token for interface authentication in Java. It is very detailed and has a certain reference value. Interested friends must read it!

Let's first introduce the idea of using JWT for authentication:

1. The user initiates a login request.

2. The server creates an encrypted JWT message and returns it as Token.

3. In the subsequent request, the JWT information is sent to the server as the request header.

4. After receiving the JWT, the server decrypts it. Correct decryption means that the request is valid and verified. If the decryption fails, the Token is invalid or expired.

The flow chart is as follows:

I. the user initiates a login request

Second, the server creates an encrypted JWT message and returns it as a Token

1. After logging in, the user returns the generated Token to the front end

Authorization@ResponseBody@GetMapping ("user/auth") public Result getUserSecurityInfo (HttpServletRequest request) {try {UserDTO userDTO =. UserVO userVO = new UserVO (); / / the method to create JWT information userVO.setToken (TokenUtil.createJWT (String.valueOf (userDTO.getId (); return Result.success (userVO);} catch (Exception e) {return Result.fail (ErrorEnum.SYSTEM_ERROR);}}

2. Create JWT,Generate Tokens

Import javax.crypto.spec.SecretKeySpec;import javax.xml.bind.DatatypeConverter;import java.security.Key;import io.jsonwebtoken.*;import java.util.Date; / / Sample method to construct a JWTprivate String createJWT (String id, String issuer, String subject, long ttlMillis) {/ / The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis (); Date now = new Date (nowMillis) / / We will sign our JWT with our ApiKey secret byte [] apiKeySecretBytes = DatatypeConverter.parseBase64Binary (apiKey.getSecret ()); Key signingKey = new SecretKeySpec (apiKeySecretBytes, signatureAlgorithm.getJcaName ()); / / Let's set the JWT Claims JwtBuilder builder = Jwts.builder (). SetId (id) .setIssuedAt (now) .setSubject (subject) .setIssuer (issuer) .signWith (signatureAlgorithm, signingKey); / / if it has been specified, let's add the expiration if (ttlMillis > = 0) {long expMillis = nowMillis + ttlMillis; Date exp = new Date (expMillis) Builder.setExpiration (exp);} / / Builds the JWT and serializes it to a compact, URL-safe string return builder.compact ();}

3. Return as Token

Look, there's a Token behind.

Third, in the subsequent request, the JWT information is sent to the server as the request header

4. After receiving the JWT, the server decrypts it. Correct decryption means that the request is valid and verified. If the decryption fails, the Token is invalid or expired.

1. Read the token value in the Header in the interceptor

@ Slf4j@Componentpublic class AuthorizationInterceptor extends HandlerInterceptorAdapter {private boolean chechToken (HttpServletRequest request, HttpServletResponse response) throws IOException {Long userId =...; if (! TokenUtil.parseJWT (request.getHeader ("Authorization"), String.valueOf (userId)) {response.setContentType ("text/html;charset=GBK"); response.setCharacterEncoding ("GBK"); response.setStatus (403); response.getWriter (). Print ("Sorry, your request is illegal, the system refuses to respond!"); return false;} else {return true;}}

2. Decrypt and verify after getting it.

Decode and Verify Tokens

Import javax.xml.bind.DatatypeConverter;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.Claims; / / Sample method to validate and read the JWTprivate void parseJWT (String jwt) {/ / This line will throw an exception if it is not a signed JWS (as expected) Claims claims = Jwts.parser () .setSigningKe y (DatatypeConverter.parseBase64Binary (apiKey.getSecret () .parseClaimsJws (jwt). GetBody (); System.out.println ("ID:" + claims.getId ()) System.out.println ("Subject:" + claims.getSubject ()); System.out.println ("Issuer:" + claims.getIssuer ()); System.out.println ("Expiration:" + claims.getExpiration ());}

The above is all the contents of the article "how to use JWT to generate Token for interface authentication in Java". Thank you for reading! Hope to share the content to help you, more related 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.

Share To

Development

Wechat

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

12
Report