JWT resource servers

An API whose users log in at an identity provider (Keycloak, Auth0, Okta, Google...) receives a JSON Web Token in Authorization: Bearer with every request, and must check it. Set the provider and the API's audience, and every request needs a valid token; scopes become SCOPE_x authorities for your rules.

Why

With tokens, the API keeps no session and never sees passwords: the provider logs users in, and the API checks a signature. That check has many traps (alg: none, an RSA key used as an HMAC secret, a token bringing its own key, an ID token used as an access token). The starter does it strictly, as Spring Security 7 does.

Example

# lib/resources/application.properties
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://login.example.com/realms/shop
spring.security.oauth2.resourceserver.jwt.audiences=orders-api

That is enough: the default chain then needs a valid bearer token on every request, and there is no default user. Or in a chain of your own:

@Bean()
SecurityFilterChain api(HttpSecurity http) => http
    .authorizeHttpRequests((auth) => auth
        .requestMatchersFor(HttpMethod.get, ['/api/orders/**']).hasAuthority('SCOPE_orders.read')
        .requestMatchersFor(HttpMethod.post, ['/api/orders/**']).hasAuthority('SCOPE_orders.write')
        .anyRequest().authenticated())
    .oauth2ResourceServer((server) => server.jwt())
    .sessionManagement((s) => s.sessionCreationPolicy(SessionCreationPolicy.stateless))
    .build();

@RestController()
class OrderController {
  @GetMapping('/api/orders/mine')
  Future<List<Order>> mine(@AuthenticationPrincipal() Jwt jwt) =>
      orders.findByOwner(jwt.subject!);
}
curl -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..." localhost:8080/api/orders/mine

Properties

Key Default Meaning
spring.security.oauth2.resourceserver.jwt.issuer-uri none The issuer of the accepted tokens; its keys come from its metadata (/.well-known/openid-configuration).
spring.security.oauth2.resourceserver.jwt.jwk-set-uri none The URL of the provider's public keys.
spring.security.oauth2.resourceserver.jwt.secret-key none The secret shared with a provider that signs with HS256, HS384 or HS512, as its UTF-8 bytes. See A shared secret. Not in Spring Boot.
spring.security.oauth2.resourceserver.jwt.jws-algorithms RS256; HS256 with secret-key The signature algorithms accepted with jwk-set-uri: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512. With secret-key, the one algorithm of the secret: HS256, HS384 or HS512. An unknown name fails the start.
spring.security.oauth2.resourceserver.jwt.audiences none A token must name one of them in aud; no audience check when empty.
spring.security.oauth2.resourceserver.jwt.required-claims.<claim> none The value a top-level claim of every token must have. See Required claims. Not in Spring Boot.
spring.security.oauth2.resourceserver.jwt.require-expiry false Whether a token without an exp claim is refused. Off, such a token never expires, as in Spring Security; set it for an issuer whose tokens always expire. Not in Spring Boot.
spring.security.oauth2.resourceserver.jwt.authority-prefix SCOPE_ Put before each authority read from the token.
spring.security.oauth2.resourceserver.jwt.authorities-claim-name scope, else scp The claim whose values are the authorities: a claim, or a path into nested objects (realm_access.roles).
spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter a space Splits a text claim into authorities.
spring.security.oauth2.resourceserver.jwt.principal-claim-name sub The claim that names the user (Authentication.name).

What is checked

In order; any failure is a 401 with WWW-Authenticate: Bearer error="invalid_token":

  1. Parsing, strictly: never alg: none, no crit header, no nested or encrypted tokens, at most 64 KiB.
  2. The algorithm must be an accepted one and fit the key, so an RSA public key is never used as an HMAC secret.
  3. The signature, with the key of the token's kid (a shared secret is one key: a kid in the header is no reason to refuse the token, the signature decides). Keys named in the token itself (jku, jwk, x5u) are ignored: a token cannot bring its own key.
  4. The type: typ is JWT (any case) or absent, as in Spring Security 7. Logout tokens, security events, DPoP proofs and at+jwt are refused. For a provider that types its access tokens at+jwt, declare a JwtDecoder bean whose validator starts with JwtTypeValidator(['at+jwt', 'JWT'], allowEmpty: true).
  5. The lifetime: exp and nbf with 60 seconds of clock skew (a token without exp passes, unless require-expiry is true); then the issuer and the audiences as configured, the required-claims, and the application's OAuth2TokenValidator<Jwt> beans.
  6. No certificate binding: a token bound to a client certificate (cnf.x5t#S256, RFC 8705) is refused, since the binding cannot be checked here.

A valid token without the rights a rule needs gets 403 with error="insufficient_scope".

The provider's keys

A shared secret

Some providers sign their tokens with a secret they share with the API (HS256) instead of a key pair. secret-key is that secret, used as its UTF-8 bytes:

spring.security.oauth2.resourceserver.jwt.secret-key=${JWT_SECRET}
# optional: only compared with the token's iss, nothing is fetched
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://login.example.com

Whoever has the secret can sign a token for any user. It belongs on a server only: never put it into a client application (a Flutter or web app, where anyone can read it), and take it from the environment, not from a file in the repository.

The application does not start when:

Only tokens of that one algorithm, signed with the secret, pass: an RS256 or ES256 token is refused whatever its signature. The claim checks are the same as with a key set.

Required claims

required-claims names claims every token must have, with the value each must equal. It works with all three ways to set the keys:

spring.security.oauth2.resourceserver.jwt.required-claims.role=authenticated
spring.security.oauth2.resourceserver.jwt.required-claims[https://example.com/tenant]=shop

Requiring an expiry

A token without exp never expires, and by default it is accepted, as in Spring Security. require-expiry=true refuses it like any other invalid token (a 401 invalid_token). It works with all three ways to set the keys:

spring.security.oauth2.resourceserver.jwt.require-expiry=true

Validators of your own

Every OAuth2TokenValidator<Jwt> bean is added to the checks of the auto-configured decoder, as in Spring Boot. None of the checks above is replaced:

@Component()
class TenantValidator implements OAuth2TokenValidator<Jwt> {
  @override
  OAuth2TokenValidatorResult validate(Jwt token) =>
      token.claims['tenant'] == 'shop'
      ? OAuth2TokenValidatorResult.success
      : OAuth2TokenValidatorResult.failure(
          const OAuth2Error('invalid_token', 'The tenant is not shop'),
        );
}

Authorities and the principal

Scopes become SCOPE_x authorities: a rule reads hasAuthority('SCOPE_orders.read'). The Authentication is a JwtAuthenticationToken whose principal is the Jwt:

Jwt member Meaning
tokenValue, headers, claims The token.
subject, issuer, audience, id, expiresAt Standard claims.
getClaimAsString(name), getClaimAsStringList(name), getClaimAsInstant(name) Typed claim reads.

Method security expressions can read principal.claims['tenant'].

To read roles from another claim, name it. When the token has no claim of exactly that name, a name with dots is a path into nested objects: realm_access.roles reads roles inside realm_access (Keycloak), app_metadata.roles reads roles inside app_metadata (Supabase). A missing part, or a part that is not an object, gives no authorities.

spring.security.oauth2.resourceserver.jwt.authorities-claim-name=realm_access.roles
spring.security.oauth2.resourceserver.jwt.authority-prefix=ROLE_

The same in code is a JwtAuthenticationConverter bean, or one set in the chain:

.oauth2ResourceServer((s) => s.jwt((j) => j.jwtAuthenticationConverter(
    const JwtAuthenticationConverter(
      authoritiesConverter: JwtGrantedAuthoritiesConverter(
        authoritiesClaimName: 'roles',
        authorityPrefix: 'ROLE_',
      ),
    ))))

A JwtDecoder bean

A JwtDecoder bean replaces the one the properties build:

@Bean()
JwtDecoder jwtDecoder() => NimbusJwtDecoder.withJwkSetUri(
      Uri.parse('https://login.example.com/jwks'),
      jwsAlgorithms: {JwsAlgorithm.rs256, JwsAlgorithm.es256},
      validator: DelegatingOAuth2TokenValidator([
        JwtValidators.createDefaultWithIssuer('https://login.example.com'),
        JwtAudienceValidator(['orders-api']),
      ]),
    );
Factory Keys
NimbusJwtDecoder.withJwkSetUri(uri, jwsAlgorithms:, validator:) The provider's JWK Set; RS256 by default; no HMAC.
NimbusJwtDecoder.withPublicKey(key, ...) One RSA public key.
NimbusJwtDecoder.withSecretKey(secret, macAlgorithm:, ...) A shared secret, HS256 to HS512; the secret must have at least as many bits as the hash.
NimbusJwtDecoder.withJwkSource(source, ...) Keys of your own source.
NimbusJwtDecoder.fromIssuerLocation(issuer) From the issuer's metadata.

Without a validator, only the type and the lifetime are checked (JwtValidators.createDefault()): add the issuer and audience checks yourself. Validators: JwtTimestampValidator, JwtIssuerValidator, JwtAudienceValidator, JwtClaimValidator, JwtTypeValidator, combined with DelegatingOAuth2TokenValidator.

The resource server options

Option Meaning
jwt((j) => ...) Required. j.decoder(decoder), j.jwtAuthenticationConverter(converter), j.authenticationManager(manager).
authenticationEntryPoint(entryPoint) What clients without a valid token get, instead of the 401.
accessDeniedHandler(handler) What token holders who are denied get, instead of the 403.
bearerTokenResolver(DefaultBearerTokenResolver(allowUriQueryParameter: true)) Also read access_token from the query of GET requests, for server-sent events from a browser. Such a token never exempts a request from CSRF.

build() fails when jwt() was not called or there is no JwtDecoder. Requests with a token in the header need no CSRF token (see CSRF). DPoP-bound tokens are accepted by the same chain (see DPoP-bound tokens).

In Spring (Java)

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://login.example.com/realms/shop
spring.security.oauth2.resourceserver.jwt.audiences=orders-api

The properties and classes are Spring Boot's and Spring Security's. Four are additions: secret-key (Spring Boot needs a JwtDecoder bean for a shared secret), required-claims, require-expiry, and a path into nested objects in authorities-claim-name (Spring's JwtGrantedAuthoritiesConverter reads a top-level claim only). Jwt implements OAuth2Token of spring_security_core. Not here yet: opaque tokens, several issuers in one chain (JwtIssuerAuthenticationManagerResolver), bearer tokens in a form body, jwt.public-key-location, and certificate-bound tokens (refused until the web starter hands client certificates to the filters).

See also