引入xml依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
生成token
@Test
void contextLoads() {
HashMap<String, Object> map = new HashMap<>();
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND,300);
String token = JWT.create()
.withHeader(map)
.withClaim("userId", "bsdf")
.withClaim("username", "tom")
.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC256("CN123"));
System.out.println(token);
}
解密token
@Test
public void test1(){
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("CN123")).build();
DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTQ1MjYxMjEsInVzZXJJZCI6ImJzZGYiLCJ1c2VybmFtZSI6InRvbSJ9.e__coiZCbznawZjPS2-N_pQmjVwiKzIeRdjPvALO8Iw");
System.out.println(verify.getClaim("userId").asString());
System.out.println(verify.getClaim("username").asString());
}