登陆JWT验证

JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案

1
2
3
4
5
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.5.0</version>
</dependency>
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
public class JwtUtil {
/**
* 过期时间为一小时
*/
private static final long EXPIRE_TIME = 60 * 60 * 1000;

/**
* 自定义token私钥
*/
private static final String TOKEN_SECRET = "joijsdfjlsjfljfljl5135313135";

/**
* 生成签名,60分钟后过期
*
* @param username
* @param userId
* @return
*/
public static String sign(String username, String userId) {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
//私钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头信息
HashMap<String, Object> header = new HashMap<>(2);
header.put("typ", "JWT");
header.put("alg", "HS256");
//附带username和userID生成签名
return JWT.create().withHeader(header).withClaim("loginName", username)
.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
}


public static DecodedJWT verity(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return jwt;
} catch (IllegalArgumentException | JWTVerificationException e) {
e.printStackTrace();
return null;
}

}

}
赏个🍗吧
0%