Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JWT to generate Token for Interface Authentication in Java

Shulou Source: shulou.com Published: 2022-06-03 09:47:49 11月15日 Update

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!

Tags: Service information generation user login interface legal content article encryption authentication value interest front end partner idea method more process Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology vpn Redmi Linux OPPO Reno