-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathJwtTokenProvider.java
More file actions
85 lines (72 loc) · 2.53 KB
/
JwtTokenProvider.java
File metadata and controls
85 lines (72 loc) · 2.53 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
package finalmission.auth.infrastructure;
import finalmission.auth.domain.AuthRole;
import finalmission.auth.domain.AuthTokenProvider;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import javax.crypto.SecretKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class JwtTokenProvider implements AuthTokenProvider {
private final SecretKey secretKey;
@Value("${security.jwt.access-token.validity-in-milliseconds}")
private long validityInMilliseconds;
public JwtTokenProvider(@Value("${security.jwt.access-token.secret-key}") final String secretKeyValue) {
this.secretKey = Keys.hmacShaKeyFor(secretKeyValue.getBytes(StandardCharsets.UTF_8));
}
public String createAccessToken(final String principal, final AuthRole role) {
Claims claims = Jwts.claims()
.subject(principal)
.build();
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()
.claims(claims)
.issuedAt(now)
.expiration(validity)
.claim("role", role.name())
.signWith(secretKey)
.compact();
}
public String getPrincipal(final String token) {
if (token == null || token.isEmpty()) {
return null;
}
return Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
}
public AuthRole getRole(final String token) {
if (token == null || token.isEmpty()) {
return AuthRole.GUEST;
}
String role = Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload()
.get("role", String.class);
return AuthRole.valueOf(role);
}
public boolean isValidToken(final String token) {
if (token == null || token.isEmpty()) {
return false;
}
try {
Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token);
return true;
} catch (JwtException e) {
return false;
}
}
}