-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathJwtTokenProvider.java
More file actions
77 lines (66 loc) · 2.64 KB
/
JwtTokenProvider.java
File metadata and controls
77 lines (66 loc) · 2.64 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
package com.example.solidconnection.auth.token;
import static com.example.solidconnection.common.exception.ErrorCode.INVALID_TOKEN;
import com.example.solidconnection.auth.domain.Subject;
import com.example.solidconnection.auth.service.TokenProvider;
import com.example.solidconnection.auth.token.config.JwtProperties;
import com.example.solidconnection.common.exception.CustomException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Date;
import java.util.Map;
import javax.crypto.SecretKey;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class JwtTokenProvider implements TokenProvider {
private final JwtProperties jwtProperties;
@Override
public String generateToken(Subject subject, Duration expireTime) {
return generateJwtTokenValue(subject.value(), Map.of(), expireTime);
}
@Override
public String generateToken(Subject subject, Map<String, String> customClaims, Duration expireTime) {
return generateJwtTokenValue(subject.value(), customClaims, expireTime);
}
private String generateJwtTokenValue(String subject, Map<String, String> claims, Duration expireTime) {
Date now = new Date();
Date expiredDate = new Date(now.getTime() + expireTime.toMillis());
JwtBuilder builder = Jwts.builder()
.subject(subject)
.issuedAt(now)
.expiration(expiredDate);
claims.forEach(builder::claim);
return builder.signWith(getSigningKey()).compact();
}
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(jwtProperties.secret().getBytes(StandardCharsets.UTF_8));
}
@Override
public Subject parseSubject(String token) {
String subject = parseJwtClaims(token).getSubject();
if (subject == null || subject.isBlank()) {
throw new CustomException(INVALID_TOKEN);
}
return new Subject(subject);
}
@Override
public <T> T parseClaims(String token, String claimName, Class<T> claimType) {
return parseJwtClaims(token).get(claimName, claimType);
}
private Claims parseJwtClaims(String token) {
try {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
} catch (Exception e) {
throw new CustomException(INVALID_TOKEN);
}
}
}