-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathJwtUtil.java
More file actions
69 lines (55 loc) · 1.72 KB
/
JwtUtil.java
File metadata and controls
69 lines (55 loc) · 1.72 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
package com.iemr.admin.utils;
import java.util.function.Function;
import javax.crypto.SecretKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String SECRET_KEY;
@Autowired
private TokenDenylist tokenDenylist;
// Generate a key using the secret
private SecretKey getSigningKey() {
if (SECRET_KEY == null || SECRET_KEY.isEmpty()) {
throw new IllegalStateException("JWT secret key is not set in application.properties");
}
return Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
}
// Validate and parse JWT Token
public Claims validateToken(String token) {
try {
Claims claims = Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
String jti = claims.getId();
// Check if token is denylisted (only if jti exists)
if (jti != null && tokenDenylist.isTokenDenylisted(jti)) {
return null;
}
return claims;
} catch (Exception e) {
return null; // Handle token parsing/validation errors
}
}
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claims != null ? claimsResolver.apply(claims) : null;
}
private Claims extractAllClaims(String token) {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
}
}