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
38
39
40
41
42
43
44
45
/**
* JWT工具类
*/
public class JwtUtils {
/**
* 签名算法
*/
private static final SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS256;
/**
* 签名密钥
*/
private static final String SECRET_KEY = "Ciallo_World";
/**
* 有效时长
*/
private static final long JWT_TOKEN_VALIDITY = 3 * 60 * 60 * 1000;

/**
* 创建JWT令牌
* @param claims 载荷
* @return JWT令牌
*/
public static String createJWT(Map<String, Object> claims) {
return Jwts.builder()
// 签名算法和密钥
.signWith(SIGNATURE_ALGORITHM, SECRET_KEY)
// 载荷
.addClaims(claims)
// 过期时间
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY))
.compact();
}

/**
* 解析JWT令牌
* @param token JWT令牌
* @return 载荷
*/
public static Claims parseJWT(String token){
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
}
}

生成令牌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 生成jwt
*/
@Test
public void testJWT() {
long time = 3 * 60 * 60 * 1000;

var claims = new HashMap<String, Object>();
claims.put("id", 1);
claims.put("name", "amane");

String token = Jwts.builder()
// 签名算法和密钥
.signWith(SignatureAlgorithm.HS256, "Ciallo_World")
// 载荷
.addClaims(claims)
// 过期时间
.setExpiration(new Date(System.currentTimeMillis() + time))
.compact();

log.info(token);
}

解析令牌

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 解析jwt
*/
@Test
public void testGetJWT() {
Claims claims = Jwts.parser()
// 密钥
.setSigningKey("Ciallo_World")
// token
.parseClaimsJws("令牌token")
.getBody();
log.info(String.valueOf(claims));
}