forked from auth0/java-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJWTSigner.java
More file actions
362 lines (322 loc) · 12.7 KB
/
JWTSigner.java
File metadata and controls
362 lines (322 loc) · 12.7 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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package com.auth0.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.*;
import java.util.*;
/**
* Handles JWT Sign Operation
*
* Default algorithm when none provided is HMAC SHA-256 ("HS256")
*
* See associated library test cases for clear examples on usage
*
*/
public class JWTSigner {
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
private byte[] secret;
private PrivateKey privateKey;
// Default algorithm HMAC SHA-256 ("HS256")
protected final static Algorithm DEFAULT_ALGORITHM = Algorithm.HS256;
public JWTSigner(final String secret) {
this(secret.getBytes());
}
public JWTSigner(final byte[] secret) {
Validate.notNull(secret);
this.secret = secret;
}
public JWTSigner(final PrivateKey privateKey) {
this.privateKey = privateKey;
}
/**
* Generate a JSON Web Token.
*
* @param claims A map of the JWT claims that form the payload. Registered claims
* must be of appropriate Java datatype as following:
* <ul>
* <li>iss, sub: String
* <li>exp, nbf, iat, jti: numeric, eg. Long
* <li>aud: String, or Collection<String>
* </ul>
* All claims with a null value are left out the JWT.
* Any claims set automatically as specified in
* the "options" parameter override claims in this map.
* @param options Allow choosing the signing algorithm, and automatic setting of some registered claims.
*/
public String sign(final Map<String, Object> claims, final Options options) {
Validate.notNull(claims);
final Algorithm algorithm = (options != null && options.algorithm != null) ? options.algorithm : DEFAULT_ALGORITHM;
final List<String> segments = new ArrayList<>();
try {
segments.add(encodedHeader(algorithm));
segments.add(encodedPayload(claims, options));
segments.add(encodedSignature(join(segments, "."), algorithm));
return join(segments, ".");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Generate a JSON Web Token using the default algorithm HMAC SHA-256 ("HS256")
* and no claims automatically set.
*/
public String sign(final Map<String, Object> claims) {
Validate.notNull(claims);
return sign(claims, null);
}
/**
* Generate the header part of a JSON web token.
*/
private String encodedHeader(final Algorithm algorithm) throws UnsupportedEncodingException {
Validate.notNull(algorithm);
// create the header
final ObjectNode header = JsonNodeFactory.instance.objectNode();
header.put("typ", "JWT");
header.put("alg", algorithm.name());
return base64UrlEncode(header.toString().getBytes("UTF-8"));
}
/**
* Generate the JSON web token payload string from the claims.
*
* @param options
*/
private String encodedPayload(final Map<String, Object> _claims, final Options options) throws IOException {
final Map<String, Object> claims = new HashMap<>(_claims);
enforceStringOrURI(claims, "iss");
enforceStringOrURI(claims, "sub");
enforceStringOrURICollection(claims, "aud");
enforceIntDate(claims, "exp");
enforceIntDate(claims, "nbf");
enforceIntDate(claims, "iat");
enforceString(claims, "jti");
if (options != null) {
processPayloadOptions(claims, options);
}
final String payload = new ObjectMapper().writeValueAsString(claims);
return base64UrlEncode(payload.getBytes("UTF-8"));
}
private void processPayloadOptions(final Map<String, Object> claims, final Options options) {
Validate.notNull(claims);
Validate.notNull(options);
final long now = System.currentTimeMillis() / 1000l;
if (options.expirySeconds != null)
claims.put("exp", now + options.expirySeconds);
if (options.notValidBeforeLeeway != null)
claims.put("nbf", now - options.notValidBeforeLeeway);
if (options.isIssuedAt())
claims.put("iat", now);
if (options.isJwtId())
claims.put("jti", UUID.randomUUID().toString());
}
// consider cleanup
private void enforceIntDate(final Map<String, Object> claims, final String claimName) {
Validate.notNull(claims);
Validate.notNull(claimName);
final Object value = handleNullValue(claims, claimName);
if (value == null)
return;
if (!(value instanceof Number)) {
throw new IllegalStateException(String.format("Claim '%s' is invalid: must be an instance of Number", claimName));
}
final long longValue = ((Number) value).longValue();
if (longValue < 0)
throw new IllegalStateException(String.format("Claim '%s' is invalid: must be non-negative", claimName));
claims.put(claimName, longValue);
}
// consider cleanup
private void enforceStringOrURICollection(final Map<String, Object> claims, final String claimName) {
final Object values = handleNullValue(claims, claimName);
if (values == null)
return;
if (values instanceof Collection) {
@SuppressWarnings({"unchecked"})
final Iterator<Object> iterator = ((Collection<Object>) values).iterator();
while (iterator.hasNext()) {
Object value = iterator.next();
String error = checkStringOrURI(value);
if (error != null)
throw new IllegalStateException(String.format("Claim 'aud' element is invalid: %s", error));
}
} else {
enforceStringOrURI(claims, "aud");
}
}
// consider cleanup
private void enforceStringOrURI(final Map<String, Object> claims, final String claimName) {
final Object value = handleNullValue(claims, claimName);
if (value == null)
return;
final String error = checkStringOrURI(value);
if (error != null)
throw new IllegalStateException(String.format("Claim '%s' is invalid: %s", claimName, error));
}
// consider cleanup
private void enforceString(final Map<String, Object> claims, final String claimName) {
final Object value = handleNullValue(claims, claimName);
if (value == null)
return;
if (!(value instanceof String))
throw new IllegalStateException(String.format("Claim '%s' is invalid: not a string", claimName));
}
// consider cleanup
private Object handleNullValue(final Map<String, Object> claims, final String claimName) {
if (!claims.containsKey(claimName))
return null;
final Object value = claims.get(claimName);
if (value == null) {
claims.remove(claimName);
return null;
}
return value;
}
// consider cleanup
private String checkStringOrURI(final Object value) {
if (!(value instanceof String))
return "not a string";
final String stringOrUri = (String) value;
if (!stringOrUri.contains(":"))
return null;
try {
new URI(stringOrUri);
} catch (URISyntaxException e) {
return "not a valid URI";
}
return null;
}
/**
* Sign the header and payload
*/
private String encodedSignature(final String signingInput, final Algorithm algorithm) throws NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException, JWTAlgorithmException {
Validate.notNull(signingInput);
Validate.notNull(algorithm);
switch (algorithm) {
case HS256:
case HS384:
case HS512:
return base64UrlEncode(signHmac(algorithm, signingInput, secret));
case RS256:
case RS384:
case RS512:
return base64UrlEncode(signRs(algorithm, signingInput, privateKey));
default:
throw new JWTAlgorithmException("Unsupported signing method");
}
}
/**
* Safe URL encode a byte array to a String
*/
private String base64UrlEncode(final byte[] str) {
Validate.notNull(str);
return new String(Base64.encodeBase64URLSafe(str));
}
/**
* Sign an input string using HMAC and return the encrypted bytes
*/
private static byte[] signHmac(final Algorithm algorithm, final String msg, final byte[] secret) throws NoSuchAlgorithmException, InvalidKeyException {
Validate.notNull(algorithm);
Validate.notNull(msg);
Validate.notNull(secret);
final Mac mac = Mac.getInstance(algorithm.getValue());
mac.init(new SecretKeySpec(secret, algorithm.getValue()));
return mac.doFinal(msg.getBytes());
}
/**
* Sign an input string using RSA and return the encrypted bytes
*/
private static byte[] signRs(final Algorithm algorithm, final String msg, final PrivateKey privateKey) throws NoSuchProviderException,
NoSuchAlgorithmException, InvalidKeyException, SignatureException {
Validate.notNull(algorithm);
Validate.notNull(msg);
Validate.notNull(privateKey);
final byte[] messageBytes = msg.getBytes();
final Signature signature = Signature.getInstance(algorithm.getValue(), "BC");
signature.initSign(privateKey);
signature.update(messageBytes);
return signature.sign();
}
private String join(final List<String> input, final String separator) {
Validate.notNull(input);
Validate.notNull(separator);
return StringUtils.join(input.iterator(), separator);
}
/**
* An option object for JWT signing operation. Allow choosing the algorithm, and/or specifying
* claims to be automatically set.
*/
public static class Options {
private Algorithm algorithm;
private Integer expirySeconds;
private Integer notValidBeforeLeeway;
private boolean issuedAt;
private boolean jwtId;
public Algorithm getAlgorithm() {
return algorithm;
}
/**
* Algorithm to sign JWT with.
*/
public Options setAlgorithm(final Algorithm algorithm) {
this.algorithm = algorithm;
return this;
}
public Integer getExpirySeconds() {
return expirySeconds;
}
/**
* Set JWT claim "exp" to current timestamp plus this value.
* Overrides content of <code>claims</code> in <code>sign()</code>.
*/
public Options setExpirySeconds(final Integer expirySeconds) {
this.expirySeconds = expirySeconds;
return this;
}
public Integer getNotValidBeforeLeeway() {
return notValidBeforeLeeway;
}
/**
* Set JWT claim "nbf" to current timestamp minus this value.
* Overrides content of <code>claims</code> in <code>sign()</code>.
*/
public Options setNotValidBeforeLeeway(final Integer notValidBeforeLeeway) {
this.notValidBeforeLeeway = notValidBeforeLeeway;
return this;
}
public boolean isIssuedAt() {
return issuedAt;
}
/**
* Set JWT claim "iat" to current timestamp. Defaults to false.
* Overrides content of <code>claims</code> in <code>sign()</code>.
*/
public Options setIssuedAt(final boolean issuedAt) {
this.issuedAt = issuedAt;
return this;
}
public boolean isJwtId() {
return jwtId;
}
/**
* Set JWT claim "jti" to a pseudo random unique value (type 4 UUID). Defaults to false.
* Overrides content of <code>claims</code> in <code>sign()</code>.
*/
public Options setJwtId(final boolean jwtId) {
this.jwtId = jwtId;
return this;
}
}
}