0%

Jwt生成token

在《用户登录页接口》中提到 Controller 类中的 Handle 方法接收到 Mybatis 返回的查询结果,通过使用Jwt来实现token计算并将计算结果返回给前端。这里记录使用 Jwt 实现token
计算的方法,世纪使用时直接复制本文代码即可。

引入依赖

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

创建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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class JwtUtil {

//有效期为(默认)
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时
//设置秘钥明文
public static final String JWT_KEY = "sangeng";

/**
* 创建token
* @param id
* @param subject
* @param ttlMillis
* @return
*/

//创建JWT,id:唯一,用uuid生成;subject:token携带数据;ttMillis:超时时间,如果为null,就给出上面的默认时间
public static String createJWT(String id, String subject, Long ttlMillis) {

SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if(ttlMillis==null){
ttlMillis=JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
SecretKey secretKey = generalKey();

JwtBuilder builder = Jwts.builder()
.setId(id) //唯一的ID
.setSubject(subject) // 主题 可以是JSON数据
.setIssuer("sg") // 签发者
.setIssuedAt(now) // 签发时间
.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
.setExpiration(expDate);// 设置过期时间
return builder.compact();
}

/**
* 生成加密后的秘钥 secretKey
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}

/**
* 解析
*
* @param jwt
* @return
* @throws Exception
*/

//解析token,获取所携带的数据就是上面的方法传入的subject
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(jwt)
.getBody();
}

public static void main(String[] args) throws Exception {
//测试,生成token字符串
String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "sangeng", null);
System.out.println(token);

//测试:解析token 如果有异常(超时、不合法token)
Claims claims = JwtUtil.parseJWT(token);
String subject = claims.getSubject();
System.out.println(subject);
}

}

Controller 类中使用上述类的静态方法

注意:传入的参数列表是 (String, String, Long) 需要转换

1
String token = JwtUtil.createJWT(UUID.randomUUID().toString(), String.valueOf(loginUser.getId()), null);