-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtTokenProvider.java
More file actions
94 lines (78 loc) · 2.95 KB
/
JwtTokenProvider.java
File metadata and controls
94 lines (78 loc) · 2.95 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
package com.example.oauth2.util;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
@Slf4j
@Component
public class JwtTokenProvider {
private final Key key;
private final long accessTokenExpireTime;
private final long refreshTokenExpireTime;
public JwtTokenProvider(@Value("${jwt.secret}") String secretKey,
@Value("${jwt.expiration}") long accessTokenExpireTime) {
byte[] keyBytes = Decoders.BASE64.decode(secretKey);
this.key = Keys.hmacShaKeyFor(keyBytes);
this.accessTokenExpireTime = accessTokenExpireTime;
this.refreshTokenExpireTime = accessTokenExpireTime * 7; // 7일
}
// Access Token 생성
public String createAccessToken(String email, String role) {
Claims claims = Jwts.claims().setSubject(email);
claims.put("role", role);
Date now = new Date();
Date expiryDate = new Date(now.getTime() + accessTokenExpireTime);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
// Refresh Token 생성
public String createRefreshToken(String email) {
Claims claims = Jwts.claims().setSubject(email);
Date now = new Date();
Date expiryDate = new Date(now.getTime() + refreshTokenExpireTime);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
// 토큰에서 이메일 추출
public String getEmailFromToken(String token) {
return getClaims(token).getSubject();
}
// 토큰에서 역할 추출
public String getRoleFromToken(String token) {
return getClaims(token).get("role", String.class);
}
// 토큰 유효성 검증
public boolean validateToken(String token) {
try {
getClaims(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
log.error("유효하지 않은 JWT 토큰: {}", e.getMessage());
return false;
}
}
// 토큰 만료 시간 확인
public boolean isTokenExpired(String token) {
Date expiration = getClaims(token).getExpiration();
return expiration.before(new Date());
}
private Claims getClaims(String token) {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
}
}