-
Notifications
You must be signed in to change notification settings - Fork 0
/
09-JwtFactory.java
56 lines (51 loc) · 1.95 KB
/
09-JwtFactory.java
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
@Service
@AllArgsConstructor
public class JwtFactory {
private final RSAKey tokenKeyRsa;
private final JwtProps jwts;
public String buildAccessToken(@NonNull UserDetailsDto user) {
try {
var claims = new JWTClaimsSet.Builder()
.audience("app")
.issuer("Auth-Service")
.issueTime(new Date())
.expirationTime(DateUtils.addMinutes(new Date(), jwts.getAccessTokenExpiresMin()))
.subject(user.getId().toString())
.claim("name", user.getName())
.claim("perm", user.getPermissions());
if (user.getLastAccountId() != null) claims.claim("acc", Map.of(
"id", user.getLastAccountId().toString(),
"name", user.getLastAccountName(),
"role", user.getLastAccountRole()));
var jwt = new SignedJWT(buildHeader(), claims.build());
jwt.sign(new RSASSASigner(tokenKeyRsa));
return jwt.serialize();
} catch (JOSEException e) {
throw new RuntimeException(e);
}
}
public String buildRefreshToken(String value) {
try {
var jwt = new JWSObject(buildHeader(), new Payload(value));
jwt.sign(new RSASSASigner(tokenKeyRsa));
return jwt.serialize();
} catch (JOSEException e) {
throw new RuntimeException(e);
}
}
public String parseRefreshToken(String value) {
try {
var jwt = JWSObject.parse(value);
var verified = jwt.verify(new RSASSAVerifier(tokenKeyRsa));
if (!verified) return null;
return jwt.getPayload().toString();
} catch (JOSEException | ParseException e) {
throw new RuntimeException(e);
}
}
private JWSHeader buildHeader() {
return new JWSHeader.Builder(JWSAlgorithm.RS256)
.keyID(tokenKeyRsa.getKeyID())
.build();
}
}