forked from auth0/java-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJWTVerifier.java
More file actions
502 lines (445 loc) · 20.2 KB
/
Copy pathJWTVerifier.java
File metadata and controls
502 lines (445 loc) · 20.2 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package com.auth0.jwt;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.impl.ExpectedCheckHolder;
import com.auth0.jwt.interfaces.Verification;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.BiPredicate;
/**
* The JWTVerifier class holds the verify method to assert that a given Token has not only a proper JWT format,
* but also its signature matches.
* <p>
* This class is thread-safe.
*
* @see com.auth0.jwt.interfaces.JWTVerifier
*/
public final class JWTVerifier implements com.auth0.jwt.interfaces.JWTVerifier {
private final Algorithm algorithm;
final List<ExpectedCheckHolder> expectedChecks;
private final JWTParser parser;
JWTVerifier(Algorithm algorithm, List<ExpectedCheckHolder> expectedChecks) {
this.algorithm = algorithm;
this.expectedChecks = Collections.unmodifiableList(expectedChecks);
this.parser = new JWTParser();
}
/**
* Initialize a {@link Verification} instance using the given Algorithm.
*
* @param algorithm the Algorithm to use on the JWT verification.
* @return a {@link Verification} instance to configure.
* @throws IllegalArgumentException if the provided algorithm is null.
*/
static Verification init(Algorithm algorithm) throws IllegalArgumentException {
return new BaseVerification(algorithm);
}
/**
* {@link Verification} implementation that accepts all the expected Claim values for verification, and
* builds a {@link com.auth0.jwt.interfaces.JWTVerifier} used to verify a JWT's signature and expected claims.
*
* Note that this class is <strong>not</strong> thread-safe. Calling {@link #build()} returns an instance of
* {@link com.auth0.jwt.interfaces.JWTVerifier} which can be reused.
*/
public static class BaseVerification implements Verification {
private final Algorithm algorithm;
private final List<ExpectedCheckHolder> expectedChecks;
private long defaultLeeway;
private final Map<String, Long> customLeeways;
private boolean ignoreIssuedAt;
private Clock clock;
BaseVerification(Algorithm algorithm) throws IllegalArgumentException {
if (algorithm == null) {
throw new IllegalArgumentException("The Algorithm cannot be null.");
}
this.algorithm = algorithm;
this.expectedChecks = new ArrayList<>();
this.customLeeways = new HashMap<>();
this.defaultLeeway = 0;
}
@Override
public Verification withIssuer(String... issuer) {
List<String> value = isNullOrEmpty(issuer) ? null : Arrays.asList(issuer);
addCheck(RegisteredClaims.ISSUER, ((claim, decodedJWT) -> {
if (verifyNull(claim, value)) {
return true;
}
if (value == null || !value.contains(claim.asString())) {
throw new IncorrectClaimException(
"The Claim 'iss' value doesn't match the required issuer.", RegisteredClaims.ISSUER, claim);
}
return true;
}));
return this;
}
@Override
public Verification withSubject(String subject) {
addCheck(RegisteredClaims.SUBJECT, (claim, decodedJWT) ->
verifyNull(claim, subject) || subject.equals(claim.asString()));
return this;
}
@Override
public Verification withAudience(String... audience) {
List<String> value = isNullOrEmpty(audience) ? null : Arrays.asList(audience);
addCheck(RegisteredClaims.AUDIENCE, ((claim, decodedJWT) -> {
if (verifyNull(claim, value)) {
return true;
}
if (!assertValidAudienceClaim(decodedJWT.getAudience(), value, true)) {
throw new IncorrectClaimException("The Claim 'aud' value doesn't contain the required audience.",
RegisteredClaims.AUDIENCE, claim);
}
return true;
}));
return this;
}
@Override
public Verification withAnyOfAudience(String... audience) {
List<String> value = isNullOrEmpty(audience) ? null : Arrays.asList(audience);
addCheck(RegisteredClaims.AUDIENCE, ((claim, decodedJWT) -> {
if (verifyNull(claim, value)) {
return true;
}
if (!assertValidAudienceClaim(decodedJWT.getAudience(), value, false)) {
throw new IncorrectClaimException("The Claim 'aud' value doesn't contain the required audience.",
RegisteredClaims.AUDIENCE, claim);
}
return true;
}));
return this;
}
@Override
public Verification acceptLeeway(long leeway) throws IllegalArgumentException {
assertPositive(leeway);
this.defaultLeeway = leeway;
return this;
}
@Override
public Verification acceptExpiresAt(long leeway) throws IllegalArgumentException {
assertPositive(leeway);
customLeeways.put(RegisteredClaims.EXPIRES_AT, leeway);
return this;
}
@Override
public Verification acceptNotBefore(long leeway) throws IllegalArgumentException {
assertPositive(leeway);
customLeeways.put(RegisteredClaims.NOT_BEFORE, leeway);
return this;
}
@Override
public Verification acceptIssuedAt(long leeway) throws IllegalArgumentException {
assertPositive(leeway);
customLeeways.put(RegisteredClaims.ISSUED_AT, leeway);
return this;
}
@Override
public Verification ignoreIssuedAt() {
this.ignoreIssuedAt = true;
return this;
}
@Override
public Verification withJWTId(String jwtId) {
addCheck(RegisteredClaims.JWT_ID, ((claim, decodedJWT) ->
verifyNull(claim, jwtId) || jwtId.equals(claim.asString())));
return this;
}
@Override
public Verification withClaimPresence(String name) throws IllegalArgumentException {
assertNonNull(name);
//since addCheck already checks presence, we just return true
withClaim(name, ((claim, decodedJWT) -> true));
return this;
}
@Override
public Verification withNullClaim(String name) throws IllegalArgumentException {
assertNonNull(name);
withClaim(name, ((claim, decodedJWT) -> claim.isNull()));
return this;
}
@Override
public Verification withClaim(String name, Boolean value) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, value)
|| value.equals(claim.asBoolean())));
return this;
}
@Override
public Verification withClaim(String name, Integer value) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, value)
|| value.equals(claim.asInt())));
return this;
}
@Override
public Verification withClaim(String name, Long value) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, value)
|| value.equals(claim.asLong())));
return this;
}
@Override
public Verification withClaim(String name, Double value) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, value)
|| value.equals(claim.asDouble())));
return this;
}
@Override
public Verification withClaim(String name, String value) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, value)
|| value.equals(claim.asString())));
return this;
}
@Override
public Verification withClaim(String name, Date value) throws IllegalArgumentException {
return withClaim(name, value != null ? value.toInstant() : null);
}
@Override
public Verification withClaim(String name, Instant value) throws IllegalArgumentException {
assertNonNull(name);
// Since date-time claims are serialized as epoch seconds,
// we need to compare them with only seconds-granularity
addCheck(name,
((claim, decodedJWT) -> verifyNull(claim, value)
|| value.truncatedTo(ChronoUnit.SECONDS).equals(claim.asInstant())));
return this;
}
@Override
public Verification withClaim(String name, BiPredicate<Claim, DecodedJWT> predicate)
throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, predicate)
|| predicate.test(claim, decodedJWT)));
return this;
}
@Override
public Verification withArrayClaim(String name, String... items) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, items)
|| assertValidCollectionClaim(claim, items)));
return this;
}
@Override
public Verification withArrayClaim(String name, Integer... items) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, items)
|| assertValidCollectionClaim(claim, items)));
return this;
}
@Override
public Verification withArrayClaim(String name, Long... items) throws IllegalArgumentException {
assertNonNull(name);
addCheck(name, ((claim, decodedJWT) -> verifyNull(claim, items)
|| assertValidCollectionClaim(claim, items)));
return this;
}
@Override
public JWTVerifier build() {
return this.build(Clock.systemUTC());
}
/**
* Creates a new and reusable instance of the JWTVerifier with the configuration already provided.
* ONLY FOR TEST PURPOSES.
*
* @param clock the instance that will handle the current time.
* @return a new JWTVerifier instance with a custom {@link java.time.Clock}
*/
public JWTVerifier build(Clock clock) {
this.clock = clock;
addMandatoryClaimChecks();
return new JWTVerifier(algorithm, expectedChecks);
}
/**
* Fetches the Leeway set for claim or returns the {@link BaseVerification#defaultLeeway}.
*
* @param name Claim for which leeway is fetched
* @return Leeway value set for the claim
*/
public long getLeewayFor(String name) {
return customLeeways.getOrDefault(name, defaultLeeway);
}
private void addMandatoryClaimChecks() {
long expiresAtLeeway = getLeewayFor(RegisteredClaims.EXPIRES_AT);
long notBeforeLeeway = getLeewayFor(RegisteredClaims.NOT_BEFORE);
long issuedAtLeeway = getLeewayFor(RegisteredClaims.ISSUED_AT);
expectedChecks.add(constructExpectedCheck(RegisteredClaims.EXPIRES_AT, (claim, decodedJWT) ->
assertValidInstantClaim(RegisteredClaims.EXPIRES_AT, claim, expiresAtLeeway, true)));
expectedChecks.add(constructExpectedCheck(RegisteredClaims.NOT_BEFORE, (claim, decodedJWT) ->
assertValidInstantClaim(RegisteredClaims.NOT_BEFORE, claim, notBeforeLeeway, false)));
if (!ignoreIssuedAt) {
expectedChecks.add(constructExpectedCheck(RegisteredClaims.ISSUED_AT, (claim, decodedJWT) ->
assertValidInstantClaim(RegisteredClaims.ISSUED_AT, claim, issuedAtLeeway, false)));
}
}
private boolean assertValidCollectionClaim(Claim claim, Object[] expectedClaimValue) {
List<Object> claimArr;
Object[] claimAsObject = claim.as(Object[].class);
// Jackson uses 'natural' mapping which uses Integer if value fits in 32 bits.
if (expectedClaimValue instanceof Long[]) {
// convert Integers to Longs for comparison with equals
claimArr = new ArrayList<>(claimAsObject.length);
for (Object cao : claimAsObject) {
if (cao instanceof Integer) {
claimArr.add(((Integer) cao).longValue());
} else {
claimArr.add(cao);
}
}
} else {
claimArr = Arrays.asList(claim.as(Object[].class));
}
List<Object> valueArr = Arrays.asList(expectedClaimValue);
return claimArr.containsAll(valueArr);
}
private boolean assertValidInstantClaim(String claimName, Claim claim, long leeway, boolean shouldBeFuture) {
Instant claimVal = claim.asInstant();
Instant now = clock.instant().truncatedTo(ChronoUnit.SECONDS);
boolean isValid;
if (shouldBeFuture) {
isValid = assertInstantIsFuture(claimVal, leeway, now);
if (!isValid) {
throw new TokenExpiredException(String.format("The Token has expired on %s.", claimVal), claimVal);
}
} else {
isValid = assertInstantIsLessThanOrEqualToNow(claimVal, leeway, now);
if (!isValid) {
throw new IncorrectClaimException(
String.format("The Token can't be used before %s.", claimVal), claimName, claim);
}
}
return true;
}
private boolean assertInstantIsFuture(Instant claimVal, long leeway, Instant now) {
long safeLeeway = Math.min(leeway, now.getEpochSecond() - Instant.MIN.getEpochSecond());
return claimVal == null || now.minus(Duration.ofSeconds(safeLeeway)).isBefore(claimVal);
}
private boolean assertInstantIsLessThanOrEqualToNow(Instant claimVal, long leeway, Instant now) {
long safeLeeway = Math.min(leeway, Instant.MAX.getEpochSecond() - now.getEpochSecond());
return !(claimVal != null && now.plus(Duration.ofSeconds(safeLeeway)).isBefore(claimVal));
}
private boolean assertValidAudienceClaim(
List<String> actualAudience,
List<String> expectedAudience,
boolean shouldContainAll
) {
if (actualAudience == null || expectedAudience == null) {
return false;
}
if (shouldContainAll) {
return actualAudience.containsAll(expectedAudience);
} else {
return !Collections.disjoint(actualAudience, expectedAudience);
}
}
private void assertPositive(long leeway) {
if (leeway < 0) {
throw new IllegalArgumentException("Leeway value can't be negative.");
}
}
private void assertNonNull(String name) {
if (name == null) {
throw new IllegalArgumentException("The Custom Claim's name can't be null.");
}
}
private void addCheck(String name, BiPredicate<Claim, DecodedJWT> predicate) {
expectedChecks.add(constructExpectedCheck(name, (claim, decodedJWT) -> {
if (claim.isMissing()) {
throw new MissingClaimException(name);
}
return predicate.test(claim, decodedJWT);
}));
}
private ExpectedCheckHolder constructExpectedCheck(String claimName, BiPredicate<Claim, DecodedJWT> check) {
return new ExpectedCheckHolder() {
@Override
public String getClaimName() {
return claimName;
}
@Override
public boolean verify(Claim claim, DecodedJWT decodedJWT) {
return check.test(claim, decodedJWT);
}
};
}
private boolean verifyNull(Claim claim, Object value) {
return value == null && claim.isNull();
}
private boolean isNullOrEmpty(String[] args) {
if (args == null || args.length == 0) {
return true;
}
boolean isAllNull = true;
for (String arg : args) {
if (arg != null) {
isAllNull = false;
break;
}
}
return isAllNull;
}
}
/**
* Perform the verification against the given Token, using any previous configured options.
*
* @param token to verify.
* @return a verified and decoded JWT.
* @throws AlgorithmMismatchException if the algorithm stated in the token's header is not equal to
* the one defined in the {@link JWTVerifier}.
* @throws SignatureVerificationException if the signature is invalid.
* @throws TokenExpiredException if the token has expired.
* @throws MissingClaimException if a claim to be verified is missing.
* @throws IncorrectClaimException if a claim contained a different value than the expected one.
*/
@Override
public DecodedJWT verify(String token) throws JWTVerificationException {
DecodedJWT jwt = new JWTDecoder(parser, token);
return verify(jwt);
}
/**
* Perform the verification against the given decoded JWT, using any previous configured options.
*
* @param jwt to verify.
* @return a verified and decoded JWT.
* @throws AlgorithmMismatchException if the algorithm stated in the token's header is not equal to
* the one defined in the {@link JWTVerifier}.
* @throws SignatureVerificationException if the signature is invalid.
* @throws TokenExpiredException if the token has expired.
* @throws MissingClaimException if a claim to be verified is missing.
* @throws IncorrectClaimException if a claim contained a different value than the expected one.
*/
@Override
public DecodedJWT verify(DecodedJWT jwt) throws JWTVerificationException {
verifyAlgorithm(jwt, algorithm);
algorithm.verify(jwt);
verifyClaims(jwt, expectedChecks);
return jwt;
}
private void verifyAlgorithm(DecodedJWT jwt, Algorithm expectedAlgorithm) throws AlgorithmMismatchException {
if (!expectedAlgorithm.getName().equals(jwt.getAlgorithm())) {
throw new AlgorithmMismatchException(
"The provided Algorithm doesn't match the one defined in the JWT's Header.");
}
}
private void verifyClaims(DecodedJWT jwt, List<ExpectedCheckHolder> expectedChecks)
throws TokenExpiredException, InvalidClaimException {
for (ExpectedCheckHolder expectedCheck : expectedChecks) {
boolean isValid;
String claimName = expectedCheck.getClaimName();
Claim claim = jwt.getClaim(claimName);
isValid = expectedCheck.verify(claim, jwt);
if (!isValid) {
throw new IncorrectClaimException(
String.format("The Claim '%s' value doesn't match the required one.", claimName),
claimName,
claim
);
}
}
}
}