001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.jose;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.internal.Limits;
021import com.revetsec.internal.http.Deadline;
022import com.revetsec.internal.jose.JwtValidationAccess;
023import com.revetsec.internal.ObserverDispatch;
024import com.revetsec.internal.jose.Algorithms;
025import com.revetsec.internal.jose.JoseFailure;
026import com.revetsec.internal.jose.JoseHeaderPolicy;
027import com.revetsec.internal.jose.JwtClaimsPolicy;
028import com.revetsec.internal.jose.JwtProcessor;
029import com.revetsec.internal.jose.KeyQuery;
030import com.revetsec.internal.jose.KeySelection;
031import com.revetsec.internal.jose.KeySelector;
032import com.revetsec.internal.jose.PreparedJws;
033import org.jspecify.annotations.NonNull;
034import org.jspecify.annotations.Nullable;
035
036import javax.annotation.concurrent.NotThreadSafe;
037import javax.annotation.concurrent.ThreadSafe;
038import java.time.Clock;
039import java.time.Duration;
040import java.util.Set;
041import java.util.function.LongSupplier;
042
043import static java.util.Objects.requireNonNull;
044
045/**
046 * Validates JWTs in the JWS compact serialization (RFC 7519, RFC 7515) signed with a public key, for one expected
047 * issuer.
048 * <p>
049 * The {@link #validateResult(String)} operation runs the checks in a fixed order and stops at the first failure:
050 * <ol>
051 *   <li>the token's length, before it is examined any further;</li>
052 *   <li>the compact serialization and the canonical base64url of every segment;</li>
053 *   <li>the JOSE header: a strict JSON object whose {@code alg} is an allowed algorithm (compared exactly, so
054 *   {@code none} in any case fails here); then no {@code crit}, {@code b64} or {@code zip}; then no key or key
055 *   location in the header ({@code jwk}, {@code jku} and {@code x5u} are rejected and never fetched); then an allowed
056 *   {@code typ}; then no {@code cty}; then a {@code kid}, when present, that is a string of 1 to 256 characters;</li>
057 *   <li>the signature's length and form for the algorithm, before any key is looked up, so a malformed signature never
058 *   causes a key set fetch;</li>
059 *   <li>the key, selected from the {@link JwksSource} by the header's {@code kid} and the algorithm; a remote
060 *   source may fetch or refresh its key set here, on the calling thread;</li>
061 *   <li>the signature, over the header and payload exactly as received;</li>
062 *   <li>the claims: a strict JSON object whose registered claims have the right types; {@code iss} equal to the
063 *   expected issuer; the key's JWK {@code issuer} member, when it has one, bound to {@code iss}; an expected audience
064 *   in {@code aud}; {@code exp}, then {@code iat}, then {@code nbf} against the clock, with the clock skew; the
065 *   required claims; and no {@code cnf}, because this validator does not check proof of possession.</li>
066 * </ol>
067 * A rejected token returns a {@link JwtValidationResult.Rejected} whose {@link JoseException.Reason} names the failed
068 * check. A remote source that cannot supply its key set throws a {@link JwksUnavailableException}, unchanged.
069 * Neither outcome nor exception diagnostics contain the token, a claim or a key ID.
070 * <p>
071 * Instances are immutable and safe for concurrent use. {@link Builder#build()} does no I/O, even over a remote key
072 * source. Validators compare by reference.
073 *
074 * @author <a href="https://www.revetkn.com">Mark Allen</a>
075 * @since 1.0.0
076 */
077@ThreadSafe
078@CheckReturnValue
079public final class JwtValidator {
080        static { JwtValidationAccess.set(new DeadlineOperations()); }
081        @ThreadSafe
082        private static final class DeadlineOperations implements JwtValidationAccess.Operations {
083                @Override public @NonNull Jwt validatePrepared(@NonNull JwtValidator validator, @NonNull PreparedJws prepared, @NonNull LongSupplier remainingNanos) {
084            long start = System.nanoTime();
085            try {
086                if (prepared.getCompactLength() > validator.headerPolicy.getMaximumTokenLength()) throw JoseException.fromReason(JoseException.Reason.TOKEN_TOO_LARGE);
087                if (!validator.headerPolicy.getAllowedAlgorithms().contains(prepared.getAlgorithm())) throw JoseException.fromReason(JoseException.Reason.ALGORITHM_NOT_ALLOWED);
088                if (!validator.headerPolicy.allowsType(prepared.findType().orElse(null))) throw JoseException.fromReason(JoseException.Reason.INVALID_TYPE);
089                Jwt jwt = Jwt.fromVerifiedJwt(JwtProcessor.complete(prepared,
090                        validator.selectKey(prepared.getKeyQuery(), requireNonNull(remainingNanos)), validator.claimsPolicy, validator.clock.instant()));
091                ObserverDispatch.dispatch(validator.observer, o -> o.didValidateJwt(jwt.getAlgorithm(), Duration.ofNanos(System.nanoTime() - start)));
092                return jwt;
093            } catch (JoseFailure failure) {
094                JoseException mapped = JoseException.fromReason(failure.getReason());
095                ObserverDispatch.dispatch(validator.observer, o -> o.didFailToValidateJwt(mapped, Duration.ofNanos(System.nanoTime() - start)));
096                throw mapped;
097            } catch (JoseException | JwksUnavailableException failure) {
098                ObserverDispatch.dispatch(validator.observer, o -> o.didFailToValidateJwt(failure, Duration.ofNanos(System.nanoTime() - start)));
099                throw failure;
100            }
101        }
102        @Override public @NonNull Jwt validateIssuerRevocation(@NonNull JwtValidator validator, @NonNull String compact, @NonNull LongSupplier remainingNanos) {
103                        return validator.validate(compact, requireNonNull(remainingNanos), validator.claimsPolicy.forIssuerRevocation());
104                }
105        @Override public @NonNull Jwt validateUserInfo(@NonNull JwtValidator validator, @NonNull String compact, @NonNull LongSupplier remainingNanos) {
106                        return validator.validate(compact, requireNonNull(remainingNanos), validator.claimsPolicy.withOptionalExpiration());
107                }
108                @Override public @NonNull Jwt validateOidc(@NonNull JwtValidator validator, @NonNull String compact, @NonNull Set<@NonNull JwsAlgorithm> algorithms,
109                                byte @NonNull [] secret, @NonNull LongSupplier remainingNanos, @NonNull Runnable hmacUsed) {
110                        JoseHeaderPolicy header = JoseHeaderPolicy.fromSettings(validator.headerPolicy.getMaximumTokenLength(),
111                                        algorithms, validator.headerPolicy.getAllowedTypes(), validator.headerPolicy.isTypeRequired());
112                        return validator.validate(compact, requireNonNull(remainingNanos), validator.claimsPolicy, header,
113                                        requireNonNull(secret), requireNonNull(hmacUsed));
114                }
115                @Override public @NonNull Jwt validateMicrosoftEntra(@NonNull JwtValidator validator, @NonNull String compact, @NonNull LongSupplier remainingNanos) {
116                        return validator.validate(compact, requireNonNull(remainingNanos), validator.claimsPolicy.withMicrosoftEntraIssuer(null));
117                }
118                @Override public @NonNull Jwt validateMicrosoftEntraUserInfo(@NonNull JwtValidator validator, @NonNull String compact,
119                                @NonNull String verifiedTenantIssuer, @NonNull LongSupplier remainingNanos) {
120                        return validator.validate(compact, requireNonNull(remainingNanos), validator.claimsPolicy.withOptionalExpiration().withMicrosoftEntraIssuer(requireNonNull(verifiedTenantIssuer)));
121                }
122                @Override public void warmUp(@NonNull RemoteJwksSource source, @NonNull LongSupplier remainingNanos) { source.warmUp(remainingNanos); }
123                @Override public @NonNull Jwt validate(@NonNull JwtValidator validator, @NonNull String compact, @NonNull LongSupplier remainingNanos) {
124                        return validator.validate(compact, requireNonNull(remainingNanos));
125                }
126        }
127
128        @NonNull
129        private static final Set<@NonNull JwsAlgorithm> DEFAULT_ALLOWED_ALGORITHMS = Set.of(JwsAlgorithm.RS256);
130        @NonNull
131        private static final Set<@NonNull String> DEFAULT_ALLOWED_TYPES = Set.of("JWT");
132
133        @NonNull
134        private final String issuer;
135        @NonNull
136        private final JwksSource jwksSource;
137        @NonNull
138        private final JoseHeaderPolicy headerPolicy;
139        @NonNull
140        private final JwtClaimsPolicy claimsPolicy;
141        private final boolean acceptAnyAudience;
142        @NonNull
143        private final Clock clock;
144        @NonNull
145        private final JoseObserver observer;
146
147        private JwtValidator(@NonNull String issuer,
148                                                                                         @NonNull JwksSource jwksSource,
149                                                                                         @NonNull JoseHeaderPolicy headerPolicy,
150                                                                                         @NonNull JwtClaimsPolicy claimsPolicy,
151                                                                                         boolean acceptAnyAudience,
152                                                                                         @NonNull Clock clock,
153                                                                                         @NonNull JoseObserver observer) {
154                this.issuer = issuer;
155                this.jwksSource = jwksSource;
156                this.headerPolicy = headerPolicy;
157                this.claimsPolicy = claimsPolicy;
158                this.acceptAnyAudience = acceptAnyAudience;
159                this.clock = clock;
160                this.observer = observer;
161        }
162
163        /**
164         * Starts building a validator for tokens from {@code issuer}.
165         *
166         * @param issuer the expected {@code iss}, compared exactly, code point by code point, with no normalization: a
167         *               trailing slash or a difference in case is another issuer
168         * @return a new builder
169         * @throws NullPointerException     if {@code issuer} is {@code null}
170         * @throws IllegalArgumentException if {@code issuer} is empty
171         * @since 1.0.0
172         */
173        @NonNull
174        public static Builder withIssuer(@NonNull String issuer) {
175                return new Builder(issuer);
176        }
177
178        /**
179         * Validates once and returns a success or a fixed local input rejection. Remote key-source failures remain
180         * exceptions; no rejected JWT, claims or credential are exposed. See the class description for the checks and
181         * their order.
182         * <p>
183         * Over a {@link RemoteJwksSource}, this may fetch the key set on the calling thread, or wait for another
184         * caller's fetch, for up to the source's request timeout.
185         *
186         * @param compactSerialization untrusted compact token
187         * @return the validation outcome
188         * @throws NullPointerException if the token is null
189         * @throws JwksUnavailableException if remote keys are unavailable
190         * @since 1.0.0
191         */
192        @CheckReturnValue
193        public @NonNull JwtValidationResult validateResult(@NonNull String compactSerialization) {
194                try {
195                        return JwtValidationResult.fromJwt(validate(compactSerialization, null));
196                } catch (JoseException rejection) {
197                        return JwtValidationResult.fromReason(rejection.getReason());
198                }
199        }
200
201        private @NonNull Jwt validate(@NonNull String compactSerialization, @Nullable LongSupplier remainingNanos) {
202                return validate(compactSerialization, remainingNanos, this.claimsPolicy);
203        }
204
205        private @NonNull Jwt validate(@NonNull String compactSerialization, @Nullable LongSupplier remainingNanos, @NonNull JwtClaimsPolicy policy) {
206                return validate(compactSerialization, remainingNanos, policy, this.headerPolicy, null, () -> { });
207        }
208
209        private @NonNull Jwt validate(@NonNull String compactSerialization, @Nullable LongSupplier remainingNanos, @NonNull JwtClaimsPolicy policy,
210                        @NonNull JoseHeaderPolicy header, byte @Nullable [] secret, @NonNull Runnable hmacUsed) {
211                requireNonNull(compactSerialization);
212                long startNanos = System.nanoTime();
213
214                if (this.acceptAnyAudience)
215                        ObserverDispatch.dispatch(this.observer, observer -> observer.didAcceptAnyAudience(this.issuer));
216
217                Jwt jwt;
218
219                try {
220                        jwt = validateOrThrow(compactSerialization, remainingNanos, policy, header, secret, hmacUsed);
221                } catch (JoseException | JwksUnavailableException exception) {
222                        Duration elapsed = Duration.ofNanos(System.nanoTime() - startNanos);
223                        ObserverDispatch.dispatch(this.observer, observer -> observer.didFailToValidateJwt(exception, elapsed));
224                        throw exception;
225                }
226
227                Duration elapsed = Duration.ofNanos(System.nanoTime() - startNanos);
228                ObserverDispatch.dispatch(this.observer, observer -> observer.didValidateJwt(jwt.getAlgorithm(), elapsed));
229                return jwt;
230        }
231
232        @NonNull
233        private Jwt validateOrThrow(@NonNull String compactSerialization, @Nullable LongSupplier remainingNanos, @NonNull JwtClaimsPolicy policy,
234                        @NonNull JoseHeaderPolicy header, byte @Nullable [] secret, @NonNull Runnable hmacUsed) {
235                try {
236                        PreparedJws prepared = JwtProcessor.prepare(compactSerialization, header);
237                        if (Algorithms.familyOf(prepared.getAlgorithm()) == Algorithms.Family.HMAC) {
238                                hmacUsed.run();
239                                return Jwt.fromVerifiedJwt(JwtProcessor.completeWithSecret(prepared, requireNonNull(secret), policy,
240                                                this.clock.instant()));
241                        }
242                        // Key resolution throws only JwksUnavailableException, which is never translated.
243                        KeySelection selection = selectKey(prepared.getKeyQuery(), remainingNanos);
244                        return Jwt.fromVerifiedJwt(JwtProcessor.complete(prepared, selection, policy,
245                                        this.clock.instant()));
246                } catch (JoseFailure failure) {
247                        throw JoseException.fromReason(failure.getReason());
248                }
249        }
250
251        @NonNull
252        private KeySelection selectKey(@NonNull KeyQuery query, @Nullable LongSupplier remainingNanos) {
253                if (this.jwksSource instanceof StaticJwksSource staticSource) {
254                        try {
255                                return KeySelector.select(staticSource.verificationKeys(), query);
256                        } catch (RuntimeException e) {
257                                // INV-G1: an unexpected failure selects no key.
258                                return KeySelection.fromKind(KeySelection.Kind.UNKNOWN);
259                        }
260                }
261
262                // A remote source throws only JwksUnavailableException, which propagates unchanged.
263                RemoteJwksSource remote = (RemoteJwksSource) this.jwksSource;
264                return remainingNanos == null ? remote.select(query) : remote.select(query,
265                                Deadline.fromNow(Duration.ofNanos(Math.max(0, remainingNanos.getAsLong()))));
266        }
267
268        /**
269         * Describes this validator's configuration.
270         *
271         * @return the issuer, the key source and the checks' settings
272         * @since 1.0.0
273         */
274        @Override
275        @NonNull
276        public String toString() {
277                return getClass().getSimpleName() + "{issuer=" + this.issuer + ", jwksSource=" + this.jwksSource
278                                + ", headerPolicy=" + this.headerPolicy + ", claimsPolicy=" + this.claimsPolicy + "}";
279        }
280
281        /**
282         * Builds a {@link JwtValidator}.
283         * <p>
284         * Each setter stores its value, and {@link #build()} checks them all. {@code null} restores a setting's default.
285         * A key source is required, and so are expected audiences unless any audience is accepted: without them
286         * {@link #build()} throws {@link IllegalStateException}. A value out of range or a conflicting pair throws
287         * {@link IllegalArgumentException}.
288         *
289         * @author <a href="https://www.revetkn.com">Mark Allen</a>
290         * @since 1.0.0
291         */
292        @NotThreadSafe
293        @CheckReturnValue
294        public static final class Builder {
295                @NonNull
296                private final String issuer;
297                @Nullable
298                private JwksSource jwksSource;
299                @Nullable
300                private Set<@NonNull String> expectedAudiences;
301                @Nullable
302                private Boolean acceptAnyAudience;
303                @Nullable
304                private Set<@NonNull JwsAlgorithm> allowedAlgorithms;
305                @Nullable
306                private Set<@NonNull String> allowedTypes;
307                @Nullable
308                private Boolean typeRequired;
309                @Nullable
310                private Set<@NonNull String> requiredClaims;
311                @Nullable
312                private Duration clockSkew;
313                @Nullable
314                private Clock clock;
315                @Nullable
316                private Integer maximumTokenLength;
317                @Nullable
318                private JoseObserver observer;
319
320                private Builder(@NonNull String issuer) {
321                        requireNonNull(issuer);
322
323                        if (issuer.isEmpty())
324                                throw new IllegalArgumentException("The issuer must not be empty.");
325
326                        this.issuer = issuer;
327                }
328
329                /**
330                 * Sets where the verification keys come from. Required.
331                 *
332                 * @param jwksSource the key source; share one only among validators with the same issuer. {@code null}
333                 *                         clears it
334                 * @return this builder
335                 * @since 1.0.0
336                 */
337                @NonNull
338                public Builder jwksSource(@Nullable JwksSource jwksSource) {
339                        this.jwksSource = jwksSource;
340                        return this;
341                }
342
343                /**
344                 * Sets the audiences a token may name: a token is accepted when at least one of its {@code aud} values is one
345                 * of these, compared exactly, and other audiences in it are allowed. Required unless any audience is accepted.
346                 *
347                 * @param expectedAudiences at least one audience, none empty; {@code null} clears them. The set is copied
348                 * @return this builder
349                 * @throws NullPointerException if the set contains {@code null}
350                 * @since 1.0.0
351                 */
352                @NonNull
353                public Builder expectedAudiences(@Nullable Set<@NonNull String> expectedAudiences) {
354                        this.expectedAudiences = expectedAudiences == null ? null : Set.copyOf(expectedAudiences);
355                        return this;
356                }
357
358                /**
359                 * Sets whether to accept a token for any audience, without checking {@code aud}. That lets a token issued for
360                 * another application of the same issuer through, so use it only when the issuer serves this application
361                 * alone. The choice is reported to {@link JoseObserver#didAcceptAnyAudience(String)} when the validator is
362                 * built and on every validation. It cannot be combined with {@link #expectedAudiences(Set)}.
363                 *
364                 * @param acceptAnyAudience whether to accept any audience; {@code null} restores the default, {@code false}
365                 * @return this builder
366                 * @since 1.0.0
367                 */
368                @NonNull
369                public Builder acceptAnyAudience(@Nullable Boolean acceptAnyAudience) {
370                        this.acceptAnyAudience = acceptAnyAudience;
371                        return this;
372                }
373
374                /**
375                 * Sets the algorithms a token may use, compared exactly with its {@code alg}.
376                 * <p>
377                 * The default allows {@code RS256} alone. Widen it only to algorithms your identity provider signs with. An RSA
378                 * key without an {@code alg} member verifies a token only while exactly one RSA algorithm is allowed, because a
379                 * key must serve one algorithm (RFC 8725 section 3.1); allowing two RSA algorithms, such as {@code RS256} and
380                 * {@code PS256}, needs keys that name their {@code alg}. Microsoft Entra ID publishes RSA keys without
381                 * {@code alg}, so they stop verifying if a second RSA algorithm is allowed (see the supported-algorithms
382                 * document).
383                 *
384                 * @param allowedAlgorithms at least one algorithm, and no HMAC algorithm: this validator verifies only with
385                 *                          public keys. {@code null} restores the default, {@code RS256}. The set is copied
386                 * @return this builder
387                 * @throws NullPointerException if the set contains {@code null}
388                 * @since 1.0.0
389                 */
390                @NonNull
391                public Builder allowedAlgorithms(@Nullable Set<@NonNull JwsAlgorithm> allowedAlgorithms) {
392                        this.allowedAlgorithms = allowedAlgorithms == null ? null : Set.copyOf(allowedAlgorithms);
393                        return this;
394                }
395
396                /**
397                 * Sets the allowed values of the header's {@code typ}. Each is a media type without parameters; a value without
398                 * {@code /} has {@code application/} implied (RFC 7515 section 4.1.9), and values are compared ignoring the case
399                 * of ASCII letters. So the default, {@code JWT}, accepts {@code JWT}, {@code jwt} and {@code application/jwt},
400                 * and rejects types that mark other profiles, such as {@code at+jwt} and {@code logout+jwt}.
401                 *
402                 * @param allowedTypes the allowed media types; may be empty, which allows only tokens without {@code typ}.
403                 *                     {@code null} restores the default, {@code JWT}. The set is copied
404                 * @return this builder
405                 * @throws NullPointerException if the set contains {@code null}
406                 * @since 1.0.0
407                 */
408                @NonNull
409                public Builder allowedTypes(@Nullable Set<@NonNull String> allowedTypes) {
410                        this.allowedTypes = allowedTypes == null ? null : Set.copyOf(allowedTypes);
411                        return this;
412                }
413
414                /**
415                 * Sets whether a token without {@code typ} is rejected.
416                 *
417                 * @param typeRequired whether the header must have {@code typ}; {@code null} restores the default,
418                 *                     {@code false}, which accepts a token without one
419                 * @return this builder
420                 * @since 1.0.0
421                 */
422                @NonNull
423                public Builder typeRequired(@Nullable Boolean typeRequired) {
424                        this.typeRequired = typeRequired;
425                        return this;
426                }
427
428                /**
429                 * Sets claims that must be present and not JSON {@code null}, besides the ones always required: {@code iss},
430                 * {@code exp}, and {@code aud} unless any audience is accepted.
431                 *
432                 * @param requiredClaims claim names, none empty; {@code null} restores the default, none. The set is copied
433                 * @return this builder
434                 * @throws NullPointerException if the set contains {@code null}
435                 * @since 1.0.0
436                 */
437                @NonNull
438                public Builder requiredClaims(@Nullable Set<@NonNull String> requiredClaims) {
439                        this.requiredClaims = requiredClaims == null ? null : Set.copyOf(requiredClaims);
440                        return this;
441                }
442
443                /**
444                 * Sets the allowance for clock differences between the issuer and this application: a token is expired from
445                 * {@code exp} plus the skew, and is not yet valid, or issued in the future, only before {@code nbf} or after
446                 * {@code iat} by more than the skew.
447                 *
448                 * @param clockSkew from zero to 5 minutes; {@code null} restores the default, 60 seconds. {@link #build()} checks
449                 *                  the range
450                 * @return this builder
451                 * @since 1.0.0
452                 */
453                @NonNull
454                public Builder clockSkew(@Nullable Duration clockSkew) {
455                        this.clockSkew = clockSkew;
456                        return this;
457                }
458
459                /**
460                 * Sets the clock that supplies the current time for the time checks.
461                 *
462                 * @param clock the clock; {@code null} restores the default, {@link Clock#systemUTC()}
463                 * @return this builder
464                 * @since 1.0.0
465                 */
466                @NonNull
467                public Builder clock(@Nullable Clock clock) {
468                        this.clock = clock;
469                        return this;
470                }
471
472                /**
473                 * Sets the longest token accepted, in characters; a longer one is rejected before it is examined.
474                 *
475                 * @param maximumTokenLength from 8,192 to 1,048,576; {@code null} restores the default, 65,536.
476                 *                           {@link #build()} checks the range
477                 * @return this builder
478                 * @since 1.0.0
479                 */
480                @NonNull
481                public Builder maximumTokenLength(@Nullable Integer maximumTokenLength) {
482                        this.maximumTokenLength = maximumTokenLength;
483                        return this;
484                }
485
486                /**
487                 * Sets the observer that receives this validator's events.
488                 *
489                 * @param observer the observer; {@code null} restores the default, {@link JoseObserver#disabledInstance()}
490                 * @return this builder
491                 * @since 1.0.0
492                 */
493                @NonNull
494                public Builder observer(@Nullable JoseObserver observer) {
495                        this.observer = observer;
496                        return this;
497                }
498
499                /**
500                 * Builds the validator. It does no I/O, even over a remote key source.
501                 *
502                 * @return a new validator
503                 * @throws IllegalArgumentException if a value is out of range: an empty set of algorithms or audiences, an
504                 *                                  HMAC algorithm, an empty audience or claim name, an allowed type that is not a
505                 *                                  media type without parameters, a required type with no allowed type, a clock
506                 *                                  skew or token length out of range; or if any audience is accepted and expected
507                 *                                  audiences are set too
508                 * @throws IllegalStateException    if no key source is set, or no expected audiences are set and any audience is
509                 *                                  not accepted
510                 * @since 1.0.0
511                 */
512                @NonNull
513                public JwtValidator build() {
514                        Set<JwsAlgorithm> algorithms = this.allowedAlgorithms == null ? DEFAULT_ALLOWED_ALGORITHMS
515                                        : this.allowedAlgorithms;
516                        if (algorithms.isEmpty())
517                                throw new IllegalArgumentException("At least one algorithm must be allowed.");
518                        for (JwsAlgorithm algorithm : algorithms)
519                                if (Algorithms.familyOf(algorithm) == Algorithms.Family.HMAC)
520                                        throw new IllegalArgumentException("A JwtValidator verifies only with public keys, so it cannot allow "
521                                                        + algorithm.getWireValue() + ".");
522
523                        boolean anyAudience = this.acceptAnyAudience != null && this.acceptAnyAudience;
524                        if (anyAudience && this.expectedAudiences != null)
525                                throw new IllegalArgumentException("Accept any audience, or set expected audiences, but not both.");
526                        if (this.expectedAudiences != null && (this.expectedAudiences.isEmpty() || this.expectedAudiences.contains("")))
527                                throw new IllegalArgumentException("Expected audiences must not be empty, and no audience may be empty.");
528
529                        Set<String> claims = this.requiredClaims == null ? Set.of() : this.requiredClaims;
530                        if (claims.contains(""))
531                                throw new IllegalArgumentException("A required claim name must not be empty.");
532
533                        Duration skew = Limits.JOSE_CLOCK_SKEW.require(this.clockSkew == null
534                                        ? Limits.JOSE_CLOCK_SKEW.getDefaultDuration() : this.clockSkew);
535                        int maximumLength = this.maximumTokenLength == null ? Limits.COMPACT_JWT_SIZE.getDefaultIntValue()
536                                        : Limits.COMPACT_JWT_SIZE.require(this.maximumTokenLength.intValue());
537                        JoseHeaderPolicy headerPolicy = JoseHeaderPolicy.fromSettings(maximumLength, algorithms,
538                                        this.allowedTypes == null ? DEFAULT_ALLOWED_TYPES : this.allowedTypes,
539                                        this.typeRequired != null && this.typeRequired);
540
541                        JwksSource source = this.jwksSource;
542                        if (source == null)
543                                throw new IllegalStateException("A JwtValidator needs a JSON Web Key source.");
544                        if (!anyAudience && this.expectedAudiences == null)
545                                throw new IllegalStateException("A JwtValidator needs expected audiences, unless it accepts any audience.");
546
547                        JwtClaimsPolicy claimsPolicy = JwtClaimsPolicy.fromSettings(this.issuer,
548                                        anyAudience ? null : this.expectedAudiences, claims, skew);
549                        JoseObserver validatorObserver = this.observer == null ? JoseObserver.disabledInstance() : this.observer;
550
551                        if (anyAudience)
552                                ObserverDispatch.dispatch(validatorObserver, observer -> observer.didAcceptAnyAudience(this.issuer));
553
554                        return new JwtValidator(this.issuer, source, headerPolicy, claimsPolicy, anyAudience,
555                                        this.clock == null ? Clock.systemUTC() : this.clock, validatorObserver);
556                }
557        }
558}