forked from JoyChou93/java-sec-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtUtils.java
More file actions
104 lines (90 loc) · 3.5 KB
/
JwtUtils.java
File metadata and controls
104 lines (90 loc) · 3.5 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
95
96
97
98
99
100
101
102
103
104
package org.joychou.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
@Slf4j
public class JwtUtils {
private static final long EXPIRE = 1440 * 60 * 1000; // 1440 Minutes, 1 DAY
private static final String SECRET = "123456";
private static final String B64_SECRET = Base64.getEncoder().encodeToString(SECRET.getBytes(StandardCharsets.UTF_8));
/**
* Generate JWT Token by jjwt (last update time: Jul 05, 2018)
*
* @author JoyChou 2022-09-20
* @param userId userid
* @return token
*/
public static String generateTokenByJjwt(String userId) {
return Jwts.builder()
.setHeaderParam("typ", "JWT") // header
.setHeaderParam("alg", "HS256") // header
.setIssuedAt(new Date()) // token发布时间
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) // token过期时间
.claim("userid", userId)
// secret在signWith会base64解码,但网上很多代码示例并没对secret做base64编码,所以在爆破key的时候可以注意下。
.signWith(SignatureAlgorithm.HS256, B64_SECRET)
.compact();
}
public static String getUserIdFromJjwtToken(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(B64_SECRET).parseClaimsJws(token).getBody();
return (String)claims.get("userid");
} catch (Exception e) {
return e.toString();
}
}
/**
* Generate jwt token by java-jwt.
*
* @author JoyChou 2022-09-20
* @param nickname nickname
* @return jwt token
*/
public static String generateTokenByJavaJwt(String nickname) {
return JWT.create()
.withClaim("nickname", nickname)
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE))
.withIssuedAt(new Date())
.sign(Algorithm.HMAC256(SECRET));
}
/**
* Verify JWT Token
* @param token token
* @return Valid token returns true. Invalid token returns false.
*/
public static Boolean verifyTokenByJavaJwt(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
} catch (JWTVerificationException exception){
log.error(exception.toString());
return false;
}
}
public static String getNicknameByJavaJwt(String token) {
// If the signature is not verified, there will be security issues.
if (!verifyTokenByJavaJwt(token)) {
log.error("token is invalid");
return null;
}
return JWT.decode(token).getClaim("nickname").asString();
}
public static void main(String[] args) {
String jjwtToken = generateTokenByJjwt("10000");
System.out.println(jjwtToken);
System.out.println(getUserIdFromJjwtToken(jjwtToken));
String token = generateTokenByJavaJwt("JoyChou");
System.out.println(token);
System.out.println(getNicknameByJavaJwt(token));
}
}