1.导入jwt pom
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.19.0</version>
</dependency>
- 生成token
HashMap<String, Object> map = new HashMap<>();
Calendar time = Calendar.getInstance();
time.add(Calendar.SECOND,10);//设置token失效时间
String token = JWT.create()
.withHeader(map)//heafer
.withClaim("username", "张三")
.withExpiresAt(time.getTime())
.sign(Algorithm.HMAC256("ascf"));//签名
System.out.println(token);
- 验证token
//创建验证对象
JWTVerifier ascf = JWT.require(Algorithm.HMAC256("ascf")).build();
DecodedJWT verify = ascf.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTczNzkyMTEsInVzZXJuYW1lIjoi5byg5LiJIn0.zzkmSvfJRvyd_u0MH75plKfqTl7n_wQ7Bp3ky2DBlV8");
System.out.println(verify.getClaim("username"));//获取token数据