引入依赖

1
2
3
4
5
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>

demo

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
public class JwtUtil {
private static final long tokenExp = 1000 * 60 * 60 * 24;
private static final String tokenSignKey = "TEST123";
// 生成token
public static String createToken(){
JwtBuilder builder = Jwts.builder();
return builder
// 头部信息
.setHeaderParam("alg","SH256")
.setHeaderParam("typ","JWT")
// 载荷:自定义信息
.claim("id",1)
.claim("phone","12323232122")
// 载荷:固定信息
.setSubject("default") // sub:令牌主题
.setIssuer("dream") // iss:签发这
.setAudience("aud") // aud:接收者
.setIssuedAt(new Date()) // jat:签发时间
.setExpiration(new Date(System.currentTimeMillis() + tokenExp)) // exp:过期时间
.setNotBefore(new Date()) // nbf:生效时间
.setId(UUID.randomUUID().toString()) // jti:唯一身份标识,主要用来回避重放攻击
// 签名哈希
.signWith(SignatureAlgorithm.HS256,tokenSignKey)
// 组装jwt
.compact();
}

// 解析jwt
public static Claims ParserToken(String token){
JwtParser parser = Jwts.parser();
Jws<Claims> claimsJws = parser.setSigningKey(tokenSignKey).parseClaimsJws(token);
return claimsJws.getBody();
}
}