Add the dependent

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.4. 0</version>
</dependency>
Copy the code

Generate JWT (Token)

public static String getToken(a) {
    // Declare expiration time: 24 hours after the current time
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.HOUR, 24);
    Date expiredTime = calendar.getTime();
    / / for JWT
    String token = JWT.create()
        // Set the Header to the default value
        .withHeader(new HashMap<String, Object>())
        / / set the content
        .withClaim("id".12345)
        .withClaim("username"."John")
        .withExpiresAt(expiredTime)
        / / set the Signature
        .sign(Algorithm.HMAC256("token12#@! KJH"));
    return token;
}
Copy the code

Verify JWT (Token)

public static void verifyToken(String token) {
    // The signature algorithm and key must be the same as when it was created
    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("token12#@! KJH")).build();
    // Verify the obtained Token. If the verification fails, the verify method will throw an exception
    DecodedJWT decodedJWT = jwtVerifier.verify(token);
    // If the validation is successful, the information in Payload can be obtained
    System.out.println(decodedJWT.getClaim("id").asLong());
    System.out.println(decodedJWT.getClaim("username").asString());
}
Copy the code

Note: Verify throws an exception:

SignatureverificationException: signature inconsistencies

TokenExpiredException: Token expiration exception

Does not match the abnormal AlgorithmMismatchException: algorithm

InvalidClaimException: Invalid payload exception

JWT Springboot integration

  1. Encapsulation JWTUtils:

    /** * JWT utility class */
    public class JWTUtils {
    
        /** * Private key */
        private static final String SECRET = "1@3$.Ssd$%7^";
    
        /** * Create Token *@paramMap User information transmitted by the foreground *@return Token
         */
        public static String getToken(Map<String, String> map) {
            JWTCreator.Builder builder = JWT.create();
    
            // Declare expiration time: 7 days
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7);
            Date expireTime = calendar.getTime();
    
            // The Header is loaded by default
            builder.withHeader(new HashMap<String, Object>());
    
            // Payload Loads data
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.withClaim(entry.getKey(), entry.getValue());
            }
            builder.withExpiresAt(expireTime);
    
            // Obtain the generated Token at the same time
            String token = builder.sign(Algorithm.HMAC256(SECRET));
    
            return token;
        }
    
        /** * Verify the validity of the Token and throw an exception * if the Token is modified@paramToken Indicates the token to be verified */
        public static void verifyToken(String token) {
            // The Token must be authenticated using the same algorithm and private key as it was created
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }
    
         /** * Get the value of the payload from the payload name *@paramToken Indicates the verified token *@paramName Key * in payload@returnValue */ in payload
         public static Claim getClaimByName(String token, String name){
             returnJWT.decode(token).getClaim(name); }}Copy the code
  2. Create an interceptor configuration class in the config package

    /** interceptor configuration class */
    @Configuration
    public class InterceptorConfig implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new JWTInterceptor())
                    // Intercept the path
                    .addPathPatterns("/ * *")
                    // Release path
                    .excludePathPatterns("/user/login")
                    .excludePathPatterns("/user/verifyCode"); }}Copy the code
  3. Configure interceptors in the Interceptor package

    /** * JWT interceptor, which protects interfaces other than login registrations. * After the user logs in, the Token is stored in the front end, and each request is brought to the back end in a Header, which is blocked by an interceptor for authentication */
    public class JWTInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // Obtain the token in the request. It is recommended to carry the token in the request header
            String token = request.getHeader("token");
            Result result;
            try {
                / / authentication token
                JWTUtils.verifyToken(token);
                // Release request
                return true;
            } catch (SignatureVerificationException e1) {
                result = Result.error(ResultCodeEnum.SIGNATURE_VERIFICATION_ERROR);
            } catch (TokenExpiredException e2) {
                result = Result.error(ResultCodeEnum.TOKEN_EXPIRED_ERROR);
            } catch (AlgorithmMismatchException e3) {
                result = Result.error(ResultCodeEnum.ALGORITHM_MISMATCH_ERROR);
            } catch (InvalidClaimException e4) {
                result = Result.error(ResultCodeEnum.INVALID_CLAIM_ERROR);
            }
            // Convert result to JSON and pass it to the front end
            String resultJson = new ObjectMapper().writeValueAsString(result);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().println(resultJson);
            // Intercept the request
            return false; }}Copy the code
  4. Interface sample

    // Do not need to receive the token, focus on business logic processing
    @GetMapping("test")
    public Result test(a) {
        // Business processing
        return Result.ok();
    }
    Copy the code

The Demo project

Github.com/AydenBryan/…