-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJWTUtil.java
More file actions
78 lines (70 loc) · 2.19 KB
/
JWTUtil.java
File metadata and controls
78 lines (70 loc) · 2.19 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
package com.xh.basic.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Date;
/**
* @author szq
* @Package com.xh.basic.utils
* @Description: JWT工具类
* @date 2018/5/217:52
*/
public class JWTUtil {
//过期时间 24小时
private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;
//秘钥
private static final String SECRET = "SHIRO+JWT";
/**
* 生成token,5min后过期
*/
public static String createToken(String username){
try{
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
//附带username信息
return JWT.create()
.withClaim("username", username)
//到期时间
.withExpiresAt(date)
//创建一个新的JWT,并使用给定的算法进行标记
.sign(algorithm);
}catch (UnsupportedEncodingException e){
return null;
}
}
/**
* 检验token是否正确
* @param token 秘钥
* @param username 用户名
* @return
*/
public static boolean verify(String token, String username){
try{
Algorithm algorithm = Algorithm.HMAC256(SECRET);
//在token中附带了username信息
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
//验证token
verifier.verify(token);
return true;
}catch (Exception exception){
return false;
}
}
/**
* 获得token中的信息,无需secret解密也能获得
* @return token中包含的用户名
*/
public static String getUsername(String token){
try{
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
}catch(JWTDecodeException e){
return null;
}
}
}