-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathStatelessTokenService.java
163 lines (147 loc) · 5.91 KB
/
StatelessTokenService.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package com.datahub.authentication.token;
import com.datahub.authentication.Actor;
import com.datahub.authentication.ActorType;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.crypto.spec.SecretKeySpec;
import static com.datahub.authentication.token.TokenClaims.*;
/**
* Service responsible for generating JWT tokens for use within DataHub in stateless way.
* This service is responsible only for generating tokens, it will not do anything else with them.
*/
public class StatelessTokenService {
protected static final long DEFAULT_EXPIRES_IN_MS = 86400000L; // One day by default
private static final List<String> SUPPORTED_ALGORITHMS = new ArrayList<>();
static {
SUPPORTED_ALGORITHMS.add("HS256"); // Only support HS256 today.
}
private final String signingKey;
private final SignatureAlgorithm signingAlgorithm;
private final String iss;
public StatelessTokenService(
@Nonnull final String signingKey,
@Nonnull final String signingAlgorithm
) {
this(signingKey, signingAlgorithm, null);
}
public StatelessTokenService(
@Nonnull final String signingKey,
@Nonnull final String signingAlgorithm,
@Nullable final String iss
) {
this.signingKey = Objects.requireNonNull(signingKey);
this.signingAlgorithm = validateAlgorithm(Objects.requireNonNull(signingAlgorithm));
this.iss = iss;
}
/**
* Generates a JWT for an actor with a default expiration time.
*
* Note that the caller of this method is expected to authorize the action of generating a token.
*
*/
public String generateAccessToken(@Nonnull final TokenType type, @Nonnull final Actor actor) {
return generateAccessToken(type, actor, DEFAULT_EXPIRES_IN_MS);
}
/**
* Generates a JWT for an actor with a specific duration in milliseconds.
*
* Note that the caller of this method is expected to authorize the action of generating a token.
*
*/
@Nonnull
public String generateAccessToken(
@Nonnull final TokenType type,
@Nonnull final Actor actor,
@Nullable final Long expiresInMs) {
Objects.requireNonNull(type);
Objects.requireNonNull(actor);
Map<String, Object> claims = new HashMap<>();
claims.put(TOKEN_VERSION_CLAIM_NAME, String.valueOf(TokenVersion.ONE.numericValue)); // Hardcode version 1 for now.
claims.put(TOKEN_TYPE_CLAIM_NAME, type.toString());
claims.put(ACTOR_TYPE_CLAIM_NAME, actor.getType());
claims.put(ACTOR_ID_CLAIM_NAME, actor.getId());
return generateAccessToken(actor.getId(), claims, expiresInMs);
}
/**
* Generates a JWT for a custom set of claims.
*
* Note that the caller of this method is expected to authorize the action of generating a token.
*/
@Nonnull
public String generateAccessToken(
@Nonnull final String sub,
@Nonnull final Map<String, Object> claims,
@Nullable final Long expiresInMs) {
Objects.requireNonNull(sub);
Objects.requireNonNull(claims);
final JwtBuilder builder = Jwts.builder()
.addClaims(claims)
.setId(UUID.randomUUID().toString())
.setSubject(sub);
if (expiresInMs != null) {
builder.setExpiration(new Date(System.currentTimeMillis() + expiresInMs));
}
if (this.iss != null) {
builder.setIssuer(this.iss);
}
byte [] apiKeySecretBytes = this.signingKey.getBytes(StandardCharsets.UTF_8);
final Key signingKey = new SecretKeySpec(apiKeySecretBytes, this.signingAlgorithm.getJcaName());
return builder.signWith(signingKey, this.signingAlgorithm).compact();
}
/**
* Validates a JWT issued by this service.
*
* Throws an {@link TokenException} in the case that the token cannot be verified.
*/
@Nonnull
public TokenClaims validateAccessToken(@Nonnull final String accessToken) throws TokenException {
Objects.requireNonNull(accessToken);
try {
byte [] apiKeySecretBytes = this.signingKey.getBytes(StandardCharsets.UTF_8);
final String base64Key = Base64.getEncoder().encodeToString(apiKeySecretBytes);
final Claims claims = (Claims) Jwts.parserBuilder()
.setSigningKey(base64Key)
.build()
.parse(accessToken)
.getBody();
final String tokenVersion = claims.get(TOKEN_VERSION_CLAIM_NAME, String.class);
final String tokenType = claims.get(TOKEN_TYPE_CLAIM_NAME, String.class);
final String actorId = claims.get(ACTOR_ID_CLAIM_NAME, String.class);
final String actorType = claims.get(ACTOR_TYPE_CLAIM_NAME, String.class);
if (tokenType != null && actorId != null && actorType != null) {
return new TokenClaims(
TokenVersion.fromNumericStringValue(tokenVersion),
TokenType.valueOf(tokenType),
ActorType.valueOf(actorType),
actorId,
claims.getExpiration() == null ? null : claims.getExpiration().getTime());
}
} catch (io.jsonwebtoken.ExpiredJwtException e) {
throw new TokenExpiredException("Failed to validate DataHub token. Token has expired.", e);
} catch (Exception e) {
throw new TokenException("Failed to validate DataHub token", e);
}
throw new TokenException("Failed to validate DataHub token: Found malformed or missing 'actor' claim.");
}
private SignatureAlgorithm validateAlgorithm(final String algorithm) {
if (!SUPPORTED_ALGORITHMS.contains(algorithm)) {
throw new UnsupportedOperationException(
String.format("Failed to create Token Service. Unsupported algorithm %s provided", algorithm));
}
return SignatureAlgorithm.valueOf(algorithm);
}
}