一、简单demo
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
@Test
public void test1() {
Map<String, Object> map = new HashMap<>();
Calendar instance = Calendar.getInstance();
instance.add(Calendar.SECOND, 60);
String token = JWT.create()
//设置头
.withHeader(map)
//设置内容
.withClaim("userId", 12)
.withClaim("userName", "xiaowang")
//过期时间
.withExpiresAt(instance.getTime())
//签名算法
.sign(Algorithm.HMAC256("sadsa555"));
System.out.println(token);
}
@Test
public void test2() {
//创建验证对象
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("sadsa555")).build();
DecodedJWT verify = verifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InhpYW93YW5nIiwiZXhwIjoxNjA1MjM2MDk3LCJ1c2VySWQiOjEyfQ.hY13p-SDWYQXMvalMBBiwd57OowR8FFNN0K13xLRzZw");
System.out.println(verify.getClaim("userId").asInt());
// System.out.println(verify.getClaims().get("userId").asString());
System.out.println(verify.getClaims().get("userName").asString());
}
二、拦截器+jwt
JwtUtils
package com.springboot.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
public class JwtUtils {
private static final String SING = "@WWQss232";
/**
* 生成token
*/
public static String getToken(Map<String,String> map){
Calendar instance = Calendar.getInstance();