#### Import dependencies

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

Encapsulated utility class

utils/JwtToken.java:

package com.blog.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.blog.entity.User;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtToken {

    /** * public key - stored on the server, the client does not know the key, to prevent attacks */
    public static String SECRET = "otyblog";


    /** * Generate token */
    public static String createToken(User user) throws Exception{

        // Issue time
        Date iatDate = new Date();

        // Expiration time -1 hour expiration
        The Calendar class is abstract and therefore cannot be instantiated by itself, so instantiation requires the use of subclasses to instantiate the GregorianCalendar object inside the getInstance method and returns it.
        Calendar nowTime = Calendar.getInstance();
        //void add(int field,int amount) adds the specified (signed) amount of time to the given calendar field according to the calendar rules
        nowTime.add(Calendar.HOUR,1);// Calendar field, the number of dates or times to add to the field.
        Date expiresDate = nowTime.getTime();// Get the expiration time

        // Header information
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("alg"."HS256");// Declare the encryption algorithm --HS256
        map.put("typ"."JWT");// Declare type -- JWT
        String token = JWT.create()
                .withHeader(map)//header
                .withClaim("userId",user.getUserId())//playload-- Stores the main useful information
                .withClaim("roleId",user.getRoleId())
                .withClaim("userName",user.getUserName())
                .withClaim("passWord",user.getPassWord())
                .withExpiresAt(expiresDate)// Set the expiration time
                .withIssuedAt(iatDate)// Issue time
                .sign(Algorithm.HMAC256(SECRET));/ / encryption
        return token;

    }


    /** * decrypt Token */
    public static Map<String, Claim> verifyToken(String token) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try{
            jwt = verifier.verify(token);
        }catch (Exception e){
            throw new RuntimeException("Token has expired, please log in again");
        }
        returnjwt.getClaims(); }}Copy the code

test

/ / test JWT
@Test
void testJWT(a) throws Exception {
    User user = new User();
    user.setUserId(1);
    user.setUserName("Zhang");
    user.setPassWord("123456");
    user.setRoleId(1);
    String token = JwtToken.createToken(user);
    System.out.println("token:"+token);

    Map<String, Claim> claimMap = JwtToken.verifyToken(token);
    System.out.println(claimMap.get("userId").asInt());
    System.out.println(claimMap.get("userName").asString());
    System.out.println(claimMap.get("passWord").asString());
    System.out.println(claimMap.get("roleId").asInt()); } output:  token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzV29yZCI6IjEyMzQ1NiIsInJvbGVJZCI6MSwidXNlck5hbWUiOiLlvKDkuIkiLCJleHAi OjE2MTczNTE4ODEsInVzZXJJZCI6MSwiaWF0IjoxNjE3MzQ4MjgxfQ.PU7SOb9jtlO1r7WHXf6aZNpApUSA_2IZtP2Pu5iBNkc1Zhang SAN123456
1
Copy the code

Reference:

  • JWT generates Token to do login verification explanation, watch to ensure you learn!
  • JWT comprehensive interpretation, use procedures