JWT的生成解析和校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class JWTConfig {

private static final String SING = "b2222c0c474c40f19a9cef972a406b8c";

/**
* 生成Token
* @param map map
* @return String
*/
public static String getToken(Map<String, String> map) {
//创建JWT
Builder jwt = JWT.create();

//设置储存数据
map.forEach(jwt::withClaim);

//设置过期时间: 7天
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE, 7);
jwt.withExpiresAt(instance.getTime());

//加密
return jwt.sign(Algorithm.HMAC256(SING));
}

/**
* 验证Token
* @param token token
* @return DecodedJWT
* @throws SignatureVerificationException 无效签名异常
* @throws TokenExpiredException token过期异常
*/
public static DecodedJWT verify(String token) throws SignatureVerificationException, TokenExpiredException {
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
}

}