Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 119 ยท Spring Boot

OAuth 2 Resource Server and Login

Secure a Spring Boot API with OAuth 2 and JWTs - resource server setup, JWKS keys, audience validation, role mapping, 401 vs 403, plus OIDC login and service-to-service tokens.

In JWT Authentication you learned what a token is and how to verify one by hand, and in Spring Security you saw the filter chain that guards every request. This lesson joins the two and adds the missing player: the authorization server. In a modern system your Spring Boot application rarely issues tokens itself. A dedicated service (Keycloak, Okta, Auth0, Microsoft Entra ID, Google, or Spring Authorization Server) logs users in and hands out tokens, and your applications play one of three roles:

  • Resource server: an API that accepts access tokens and enforces what they allow. This is the main subject of the lesson.
  • Client with login (single sign-on): a server-rendered web app that sends users to the authorization server and receives their identity back.
  • Client for service-to-service calls: a back-end job that fetches its own token to call another API.

Spring Security supports all three declaratively. The examples that run here rebuild the interesting mechanics (key lookup by kid, authority mapping, the 401 and 403 responses) in plain Java, so you understand what the starters do for you.

The cast and the flow

sequenceDiagram
  participant U as User / client app
  participant A as Authorization server
  participant R as Resource server (your API)
  U->>A: log in (Authorization Code + PKCE)
  A-->>U: access token (JWT)
  U->>R: GET /api/books + Authorization: Bearer token
  R->>A: fetch public keys (JWKS), once, then cached
  A-->>R: key set
  R->>R: verify signature, exp, iss, aud, then map scopes to authorities
  R-->>U: 200 OK (or 401 / 403)

The API never sees the user's password and never talks to the authorization server per request; it only needs the server's public keys.

That last point is the great strength of JWT access tokens: validation is a local computation with a cached public key, so the authorization server is not in the request path.

Setting up a resource server

Add the resource-server starter (spring-boot-starter-security-oauth2-resource-server in Boot 4; in Boot 3 it is spring-boot-starter-oauth2-resource-server) and point it at your issuer:

YAML
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.example.com/realms/library
          audiences: library-api

With issuer-uri, Spring finds the signing keys by reading https://auth.example.com/realms/library/.well-known/openid-configuration, which names the jwks_uri, and it adds an issuer check to the validators. The discovery happens lazily, on the first token, so your API can start while the authorization server is down. If your provider offers no discovery document, set jwk-set-uri instead; then you must add the issuer validation yourself.

The default validation covers the signature, the exp and nbf times (with 60 seconds of clock-skew tolerance) and, with the properties above, iss and aud. Anything else needs a custom validator. The most common addition, checking the audience, looks like this when you configure the decoder yourself:

Java
@Bean
JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuer) {
    NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation(issuer);

    OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(
        "aud", aud -> aud != null && aud.contains("library-api"));

    decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
        JwtValidators.createDefaultWithIssuer(issuer), audience));
    return decoder;
}

Always check the audience. A token issued for the billing API is perfectly signed by the same authorization server. Without an aud check, your library API would accept it.

The filter chain is the one from the earlier lessons, with the resource-server DSL switched on:

Java
@Configuration
@EnableMethodSecurity
class ApiSecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http, JwtAuthenticationConverter converter) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/books/**").hasAuthority("SCOPE_books.read")
                .requestMatchers("/api/books/**").hasAuthority("SCOPE_books.write")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(converter)))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable())   // bearer tokens are not sent automatically by browsers
            .build();
    }
}

BearerTokenAuthenticationFilter extracts the token from the Authorization: Bearer ... header, the JwtDecoder validates it, the converter turns it into an Authentication whose principal is the Jwt, and everything after that is the normal authorization you already know.

Keys and rotation: how the JWKS cache works

Authorization servers rotate signing keys regularly. Each token header carries a kid (key id), and the server publishes the current public keys as a JSON Web Key Set (JWKS). A resource server therefore does three things: caches the key set (fetching it on every request would make the authorization server the bottleneck), looks the key up by kid, and when it sees a kid it doesn't know, refreshes the set once because a rotation may just have happened. It must not refresh for every bogus token, or an attacker could force it to hammer the authorization server.

Spring's Nimbus-based decoder implements this. The simulation below does the same with real RSA signatures, and counts the downloads:

Java A JWKS cache that refreshes on an unknown kid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 3 triggered exactly one extra download and then step 4 used the cache. Step 5 shows that a known kid with a wrong signature fails without any download. Step 6 shows the cost of an invented kid: one refresh. Real implementations add a minimum interval between refreshes (Nimbus rate-limits the JWKS retrieval) so a flood of bogus tokens can't turn into a flood of downloads.

From claims to authorities

A validated token is just claims. Authorization needs authorities. By default, Spring reads the scope claim (a space-separated string) or the scp claim (a list) and creates one authority per entry, prefixed with SCOPE_: the scope books.read becomes SCOPE_books.read, matching hasAuthority("SCOPE_books.read").

Roles are less standardized. Keycloak puts them in realm_access.roles, Auth0 and Okta usually in a custom claim such as roles or groups, and Entra ID in roles. You decide where your roles come from by providing a converter:

Java
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter scopes = new JwtGrantedAuthoritiesConverter();   // SCOPE_ from scope / scp

    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(jwt -> {
        Collection<GrantedAuthority> authorities = new ArrayList<>(scopes.convert(jwt));
        Map<String, Object> realmAccess = jwt.getClaim("realm_access");
        if (realmAccess != null && realmAccess.get("roles") instanceof Collection<?> roles) {
            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role)));
        }
        return authorities;
    });
    return converter;
}

Here is the same logic as a plain Java function, so you can experiment with different token shapes:

Java Mapping scope and role claims to authorities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Keep roles (what a person is) and scopes (what a client may do for the person) in mind separately. A delete operation often requires both: the client was allowed to write (scope) and the user is a librarian (role). That is exactly the @PreAuthorize("hasAuthority('SCOPE_books.write') and hasRole('LIBRARIAN')") rule from Spring Security.

401, 403 and the WWW-Authenticate header

The two failure codes mean different things, and clients rely on them:

  • 401 Unauthorized: "I don't know who you are." No token, an expired token, a bad signature. The response carries WWW-Authenticate: Bearer and, when a token was present, error="invalid_token" with a description. A client reacts by refreshing the token or logging in again.
  • 403 Forbidden: "I know who you are, and you may not do this." The token is valid but lacks the scope or role. The response can carry error="insufficient_scope". Logging in again won't help.

Spring produces both automatically: BearerTokenAuthenticationEntryPoint for 401 and BearerTokenAccessDeniedHandler for 403. The server below mimics them with a JDK HttpServer and a tiny token table, and a client shows what each failure looks like on the wire:

Java 401 versus 403 with a Bearer token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When you write a client, use the codes as intended: on 401 refresh the token once and retry; on 403 show "not allowed" and don't retry.

Opaque tokens as an alternative

Not every authorization server issues JWTs. An opaque token is a random string with no readable content; the only way to learn what it means is to ask the authorization server through token introspection (RFC 7662). Spring supports it with the same DSL:

YAML
spring:
  security:
    oauth2:
      resourceserver:
        opaquetoken:
          introspection-uri: https://auth.example.com/oauth2/introspect
          client-id: library-api
          client-secret: ${INTROSPECTION_SECRET}
Java
http.oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults()));

Trade-offs: opaque tokens can be revoked immediately (the server just answers active: false) and leak no claims, but every request costs a network call unless you cache the introspection result briefly. JWTs are validated locally but stay valid until they expire, so keep their lifetime short (minutes). You can use only one of the two styles per filter chain.

Single sign-on for a web application

A server-rendered application with pages (Thymeleaf, for example) has a different job: log the user in through the authorization server using OpenID Connect and keep a normal session. That is oauth2Login, from the OAuth 2 client starter (spring-boot-starter-security-oauth2-client; the Boot 3 name is spring-boot-starter-oauth2-client):

YAML
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: library-web
            client-secret: ${LIBRARY_WEB_SECRET}
            scope: openid,profile,email
        provider:
          keycloak:
            issuer-uri: https://auth.example.com/realms/library
Java
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    return http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/", "/css/**").permitAll()
            .anyRequest().authenticated())
        .oauth2Login(Customizer.withDefaults())
        .logout(logout -> logout.logoutSuccessUrl("/"))
        .build();
}

@Controller
class ProfileController {
    @GetMapping("/profile")
    String profile(@AuthenticationPrincipal OidcUser user, Model model) {
        model.addAttribute("name", user.getFullName());
        model.addAttribute("email", user.getEmail());
        return "profile";
    }
}

With this in place, an anonymous visit to /profile redirects to the authorization server's login page (/oauth2/authorization/keycloak starts the flow), the user signs in, and the provider redirects back to /login/oauth2/code/keycloak, where Spring exchanges the code for tokens, validates the ID token and creates the session. Register that redirect URI at the provider. For the full logout, including ending the provider's session, add OidcClientInitiatedLogoutSuccessHandler.

The browser flow and the API flow need different filter chains: sessions and redirects for pages, stateless bearer tokens for /api/**. When one application serves both, define two SecurityFilterChain beans with @Order and give the first a securityMatcher("/api/**"):

flowchart TD
  R["Incoming request"] --> M{"path starts with<br/>/api/ ?"}
  M -- yes --> A["Chain 1 (order 1)<br/>oauth2ResourceServer, stateless,<br/>401 / 403 responses"]
  M -- no --> W["Chain 2 (order 2)<br/>oauth2Login, session,<br/>redirects to login"]

Spring Security uses the first chain whose matcher accepts the request.

Calling other APIs with a service token

When a back-end job or service calls another protected API on its own behalf (no user involved), it uses the Client Credentials grant: it authenticates to the authorization server with its client id and secret and receives an access token. Register it like a login client, with a different grant type:

YAML
spring:
  security:
    oauth2:
      client:
        registration:
          billing:
            provider: keycloak
            client-id: library-service
            client-secret: ${LIBRARY_SERVICE_SECRET}
            authorization-grant-type: client_credentials
            scope: invoices.write

Outside an HTTP request (a scheduler, for instance) use the service-based manager, which caches the token and requests a new one shortly before it expires:

Java
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository registrations,
                                                      OAuth2AuthorizedClientService clients) {
    var manager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(registrations, clients);
    manager.setAuthorizedClientProvider(OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build());
    return manager;
}

String billingToken(OAuth2AuthorizedClientManager manager) {
    OAuth2AuthorizeRequest request = OAuth2AuthorizeRequest.withClientRegistrationId("billing")
        .principal("library-service")
        .build();
    return manager.authorize(request).getAccessToken().getTokenValue();
}

You then send that token as Authorization: Bearer ... with a RestClient, as in HTTP Client in Depth. Recent Spring Security versions also ship a request interceptor that attaches the token for you; check the reference for your version.

Common mistakes

  • Skipping the audience check, so tokens meant for another API are accepted.
  • Issuer mismatch behind a proxy. The iss claim must equal issuer-uri character for character, including scheme, host, port and trailing slash. A token issued for http://keycloak:8080/... inside Docker will not match https://auth.example.com/....
  • Long-lived access tokens. A JWT cannot be revoked before it expires. Keep lifetimes short and use refresh tokens in the client.
  • Putting secrets or personal data in the token. A JWT is signed, not encrypted; anyone holding it can read it.
  • Letting the SPA hold client secrets. Public clients (single-page apps, mobile) use PKCE and no secret.
  • Forgetting CORS. A browser app on another origin needs a CorsConfigurationSource bean and .cors(Customizer.withDefaults()), otherwise preflight OPTIONS requests (which carry no token) are rejected with 401.
  • Testing with real tokens. Use spring-security-test: mockMvc.perform(get("/api/books").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_books.read")))), as shown in Testing Spring Boot Applications.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a resource server validate a JWT without contacting the authorization server for each request?

    Public-key signatures can be checked locally. The key set is cached and refreshed only when an unknown kid appears.
  2. 2. A request carries a valid, unexpired token, but it lacks the scope books.write needed for DELETE. What should the API return?

    401 means the caller could not be authenticated; 403 means the caller is known but not permitted. A new login or refresh would not help.
  3. 3. Which setting protects your API from accepting a correctly signed token that was issued for a different API?

    All APIs trusting the same authorization server see validly signed tokens. The aud claim says which API a token is meant for.
  4. 4. Your Keycloak tokens carry roles in realm_access.roles, but hasRole('LIBRARIAN') never matches. What is missing?

    By default only scope or scp become authorities (SCOPE_...). Roles live in provider-specific claims, so you map them yourself.
  5. 5. What is the right tool for a nightly job that calls another protected API with no user involved?

    Client Credentials gives the service its own identity and token, which can be limited with scopes and rotated independently of any user.

Summary

  • A resource server validates bearer tokens: signature (via cached JWKS public keys, refreshed once on an unknown kid), expiry, iss and, with your help, aud.
  • Configure it with issuer-uri (and audiences), plug a JwtDecoder validator for custom checks, and map claims to authorities with a JwtAuthenticationConverter (SCOPE_ for scopes, ROLE_ for roles from provider-specific claims).
  • 401 means authentication failed (refresh or log in); 403 means the caller lacks permission (don't retry). Spring sends the correct WWW-Authenticate header for both.
  • Opaque tokens use introspection: instantly revocable, but one network call per token (cache it).
  • oauth2Login gives web apps single sign-on through OpenID Connect; use separate SecurityFilterChain beans for /api/** and for pages.
  • Services call other APIs with the Client Credentials grant and an OAuth2AuthorizedClientManager that caches and renews tokens.
  • Keep access tokens short-lived, check audience and issuer exactly, and never put secrets in a JWT.

Next: Batch Processing with Spring Batch shows how to process millions of records reliably, in chunks, with restart and skip support.