TokenUtils.java
2.66 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.sincere.wechatbusiness.utils;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.util.Date;
import java.util.Objects;
public class TokenUtils {
/**
* 创建秘钥
*/
private static final byte[] SECRET = "6MNSobBRCHGIO0fS6MNSobBRCHGWO0fS".getBytes();
/**
* 过期时间5秒
*/
private static final long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 3;
/**
* 生成Token 入参userId
* @param account
* @return
*/
public static String buildToken(String account) {
try {
/**
* 1.创建一个32-byte的密匙
*/
MACSigner macSigner = new MACSigner(SECRET);
/**
* 2. 建立payload 载体
*/
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.expirationTime(new Date(System.currentTimeMillis() + EXPIRE_TIME))
.claim("ACCOUNT",account)
.build();
/**
* 3. 建立签名
*/
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
signedJWT.sign(macSigner);
/**
* 4. 生成token
*/
String token = signedJWT.serialize();
return token;
} catch (KeyLengthException e) {
e.printStackTrace();
} catch (JOSEException e) {
e.printStackTrace();
}
return null;
}
/**
* 校验token
* @param token
* @return
*/
public static String validToken(String token) throws ResultException {
try {
SignedJWT jwt = SignedJWT.parse(token);
JWSVerifier verifier = new MACVerifier(SECRET);
//校验是否有效
if (!jwt.verify(verifier)) {
throw new ResultException(-1, "Token 无效");
}
//校验超时
Date expirationTime = jwt.getJWTClaimsSet().getExpirationTime();
if (new Date().after(expirationTime)) {
throw new ResultException(-2, "Token 已过期");
}
//获取载体中的数据
Object account = jwt.getJWTClaimsSet().getClaim("ACCOUNT");
//是否有openUid
if (Objects.isNull(account)){
throw new ResultException(-3, "账号为空");
}
return account.toString();
} catch (Exception e) {
throw new ResultException(-4, "系统繁忙");
}
}
}