OAuth2 and OpenID Connect in Spring Boot: APIs that trust tokens, apps that log users in

With OAuth2, users log in at an identity provider such as Keycloak, Okta or Entra ID, and your applications receive tokens instead of passwords. Spring Security plays two roles: a resource server that checks tokens on API calls, and a client that runs the login flow for a web application. This page runs both against a small identity provider started inside each program, so every request and response is real.

Contents

OAuth2 and OpenID Connect in one page of concepts

OAuth2 is a protocol for handing out access tokens. OpenID Connect (OIDC) builds on it to say who the user is. Four parties take part:

  • Resource owner: the user.
  • Authorization server, often called the identity provider: Keycloak, Okta, Auth0, Entra ID, Google. It checks the user's password, asks for consent, and issues tokens.
  • Client: the application the user logs in to, such as a web app. It sends the user to the provider and receives tokens back.
  • Resource server: an API that accepts access tokens and checks them on every call.

Spring Security covers the last two roles; Spring Authorization Server, a separate project, covers the second. The tokens involved:

Tokens in OAuth2 and OIDC
TokenFormatAudienceUsed for
Access tokenUsually a JWT; sometimes opaqueThe API (resource server)Authorization: Bearer on API calls
ID token (OIDC)Always a JWTThe clientTelling the client who logged in; never sent to APIs
Refresh tokenOpaqueThe authorization serverGetting new access tokens without a new login

In Spring Boot 4 the two roles have separate starters: spring-boot-starter-security-oauth2-resource-server and spring-boot-starter-security-oauth2-client. In Spring Boot 3.x they were called spring-boot-starter-oauth2-resource-server and spring-boot-starter-oauth2-client; the configuration properties under spring.security.oauth2 keep their names. The examples use Spring Security 7.1.2. A real identity provider cannot run inside these programs, so each one starts a small stand-in with the JDK's built-in HTTP server. It serves the same endpoints a real provider does (discovery, keys, authorize, token, userinfo, introspection) and prints what it receives, so the traffic between Spring and the provider is visible.

A JWT resource server configured by issuer-uri

The common setup for an API is one property, the provider's issuer address. Spring then discovers everything else. This program starts the stand-in provider, starts the API with issuer-uri and audiences, and sends six tokens, one per rule a resource server enforces:

Java
package demo.oauth2.issuer;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

public class IssuerResourceServer {

    /** A stand-in identity provider: discovery document and public keys over HTTP. */
    static HttpServer startProvider(RSAKey key) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        String issuer = "http://localhost:" + server.getAddress().getPort() + "/realms/shop";
        String discovery = "{\"issuer\":\"" + issuer + "\",\"jwks_uri\":\"" + issuer
                + "/certs\",\"subject_types_supported\":[\"public\"]}";
        String jwks = new JWKSet(key.toPublicJWK()).toString();
        server.createContext("/realms/shop/.well-known/openid-configuration",
                exchange -> respond(exchange, discovery));
        server.createContext("/realms/shop/certs", exchange -> respond(exchange, jwks));
        server.start();
        return server;
    }

    static void respond(HttpExchange exchange, String json) throws IOException {
        System.out.println("    [provider] GET " + exchange.getRequestURI().getPath()
                .replaceAll(".*/realms", "/realms"));
        byte[] body = json.getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().add("Content-Type", "application/json");
        exchange.sendResponseHeaders(200, body.length);
        exchange.getResponseBody().write(body);
        exchange.close();
    }

    @RestController
    static class OrderController {
        @GetMapping("/api/orders")
        String list(@AuthenticationPrincipal Jwt jwt) {
            return "orders of " + jwt.getSubject();
        }

        @PostMapping("/api/orders")
        String create() {
            return "order created";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(OrderController.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/error").permitAll()
                            .requestMatchers(HttpMethod.POST, "/api/orders")
                            .hasAuthority("SCOPE_orders.write")
                            .anyRequest().hasAuthority("SCOPE_orders.read"))
                    .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()));
            return http.build();
        }
    }

    public static void main(String[] args) throws Exception {
        RSAKey key = new RSAKeyGenerator(2048).keyID("shop-key-1").generate();
        HttpServer provider = startProvider(key);
        String issuer = "http://localhost:" + provider.getAddress().getPort() + "/realms/shop";
        NimbusJwtEncoder signer = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));

        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.security.oauth2.resourceserver.jwt.issuer-uri", issuer,
                "spring.security.oauth2.resourceserver.jwt.audiences", "orders-api"));
        System.out.println("Starting the application:");
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            Instant now = Instant.now();
            record Case(String label, String method, String iss, String aud, String scope,
                        Instant exp) {
            }
            List<Case> cases = List.of(
                    new Case("valid token, scope orders.read", "GET", issuer, "orders-api",
                            "orders.read", now.plusSeconds(300)),
                    new Case("same token, POST needs orders.write", "POST", issuer,
                            "orders-api", "orders.read", now.plusSeconds(300)),
                    new Case("scope orders.read orders.write", "POST", issuer, "orders-api",
                            "orders.read orders.write", now.plusSeconds(300)),
                    new Case("token for another API (aud)", "GET", issuer, "billing-api",
                            "orders.read", now.plusSeconds(300)),
                    new Case("token from another issuer", "GET", "https://evil.example.net",
                            "orders-api", "orders.read", now.plusSeconds(300)),
                    new Case("expired 10 minutes ago", "GET", issuer, "orders-api",
                            "orders.read", now.minus(Duration.ofMinutes(10))));
            System.out.println("Calls:");
            for (Case c : cases) {
                String token = signer.encode(JwtEncoderParameters.from(
                        JwsHeader.with(SignatureAlgorithm.RS256).keyId("shop-key-1").build(),
                        JwtClaimsSet.builder().issuer(c.iss()).subject("ann")
                                .audience(List.of(c.aud())).claim("scope", c.scope())
                                .issuedAt(c.exp().minusSeconds(300)).expiresAt(c.exp())
                                .build())).getTokenValue();
                HttpResponse<String> r = HttpClient.newHttpClient().send(
                        HttpRequest.newBuilder(URI.create(base + "/api/orders"))
                                .header("Authorization", "Bearer " + token)
                                .method(c.method(), HttpRequest.BodyPublishers.noBody()).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("  " + c.label() + " -> " + r.statusCode()
                        + (r.statusCode() == 200 ? " " + r.body() : ""));
                r.headers().firstValue("WWW-Authenticate")
                        .map(h -> h.replaceAll(", error_uri=\"[^\"]*\"", "")
                                .replaceAll(",? ?resource_metadata=\"[^\"]*\"", "")
                                .replaceAll("expired at [^\"]*", "expired at TIME"))
                        .ifPresent(h -> System.out.println("      " + h));
            }
        } finally {
            provider.stop(0);
        }
    }
}
Output
Starting the application:
Calls:
    [provider] GET /realms/shop/.well-known/openid-configuration
    [provider] GET /realms/shop/certs
  valid token, scope orders.read -> 200 orders of ann
  same token, POST needs orders.write -> 403
      Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."
  scope orders.read orders.write -> 200 order created
  token for another API (aud) -> 401
      Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: The aud claim is not valid"
  token from another issuer -> 401
      Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: The iss claim is not valid"
  expired 10 minutes ago -> 401
      Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Jwt expired at TIME"
  • The provider received no requests while the application started. On the first API call, Spring fetched /.well-known/openid-configuration, found the jwks_uri in it, and fetched the public keys from /certs. Later calls used the cached keys and caused no provider traffic.
  • A valid token with the scope orders.read was accepted, and the controller read sub from the Jwt principal: orders of ann.
  • The same token on POST got 403 with error="insufficient_scope": the signature was fine, but the rule wants SCOPE_orders.write. The resource server turns each space-separated value of scope into a SCOPE_ authority.
  • A token whose aud is billing-api got 401 The aud claim is not valid, because of the audiences property. Without that check, a token issued for any application of the same provider would be accepted by this API.
  • Tokens from another issuer, or expired ones, got 401 with invalid_token and the reason.

The POST worked without a CSRF token, although CSRF protection is on: the resource server excludes requests that carry a bearer token from the CSRF check, since a browser never adds such a header by itself. The configuration in application.yml form:

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

Use jwk-set-uri instead of issuer-uri when the provider has no discovery document, and public-key-location for a fixed key file. With jwk-set-uri alone, set the issuer check yourself, because there is no issuer to compare with.

Mapping claims to roles and user names

Providers put roles in different claims: Keycloak uses realm_access.roles, Entra ID uses roles, Auth0 uses a namespaced custom claim. Spring Security reads only scope (or scp) by default. This program converts the same Keycloak-style token with the default converter and with a customised one:

Java
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.core.convert.converter.Converter;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
// The two class names below would make the import lines longer than 100 characters.
import org.springframework.security.oauth2.server.resource.authentication.*;

public class ClaimsToAuthorities {

    /** Reads Keycloak's realm_access.roles claim and turns each role into ROLE_name. */
    static Collection<GrantedAuthority> realmRoles(Jwt jwt) {
        Map<String, Object> realmAccess = jwt.getClaimAsMap("realm_access");
        List<GrantedAuthority> roles = new ArrayList<>();
        if (realmAccess != null && realmAccess.get("roles") instanceof List<?> names) {
            names.forEach(n -> roles.add(new SimpleGrantedAuthority("ROLE_" + n)));
        }
        return roles;
    }

    static void show(String label, Converter<Jwt, AbstractAuthenticationToken> converter,
                     Jwt jwt) {
        AbstractAuthenticationToken auth = converter.convert(jwt);
        System.out.println(label);
        System.out.println("  name       : " + auth.getName());
        System.out.println("  authorities: " + auth.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority).sorted().toList());
    }

    public static void main(String[] args) throws Exception {
        RSAKey key = new RSAKeyGenerator(2048).keyID("k1").generate();
        String token = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)))
                .encode(JwtEncoderParameters.from(
                        JwsHeader.with(SignatureAlgorithm.RS256).keyId("k1").build(),
                        JwtClaimsSet.builder()
                                .subject("f1c2a7e0-3b9d-4c55-9a1e-2d7c8b6a4f10")
                                .claim("preferred_username", "ann")
                                .claim("scope", "openid profile orders.read")
                                .claim("realm_access", Map.of("roles", List.of("admin", "user")))
                                .expiresAt(Instant.parse("2099-01-01T00:00:00Z"))
                                .build()))
                .getTokenValue();
        JwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key.toRSAPublicKey()).build();
        Jwt jwt = decoder.decode(token);
        System.out.println("Claims: " + new TreeMap<>(jwt.getClaims()).keySet());

        show("Default JwtAuthenticationConverter:", new JwtAuthenticationConverter(), jwt);

        JwtAuthenticationConverter custom = new JwtAuthenticationConverter();
        JwtGrantedAuthoritiesConverter scopes = new JwtGrantedAuthoritiesConverter();
        custom.setJwtGrantedAuthoritiesConverter(j -> {
            List<GrantedAuthority> all = new ArrayList<>(scopes.convert(j));
            all.addAll(realmRoles(j));
            return all;
        });
        custom.setPrincipalClaimName("preferred_username");
        show("With realm roles and preferred_username:", custom, jwt);

        ExpressionJwtGrantedAuthoritiesConverter byExpression =
                new ExpressionJwtGrantedAuthoritiesConverter(
                        new SpelExpressionParser().parseExpression("[realm_access][roles]"));
        byExpression.setAuthorityPrefix("ROLE_");
        JwtAuthenticationConverter expression = new JwtAuthenticationConverter();
        expression.setJwtGrantedAuthoritiesConverter(byExpression);
        show("With the SpEL expression [realm_access][roles]:", expression, jwt);
    }
}
Output
Claims: [exp, iat, preferred_username, realm_access, scope, sub]
Default JwtAuthenticationConverter:
  name       : f1c2a7e0-3b9d-4c55-9a1e-2d7c8b6a4f10
  authorities: [FACTOR_BEARER, SCOPE_openid, SCOPE_orders.read, SCOPE_profile]
With realm roles and preferred_username:
  name       : ann
  authorities: [FACTOR_BEARER, ROLE_admin, ROLE_user, SCOPE_openid, SCOPE_orders.read, SCOPE_profile]
With the SpEL expression [realm_access][roles]:
  name       : f1c2a7e0-3b9d-4c55-9a1e-2d7c8b6a4f10
  authorities: [FACTOR_BEARER, ROLE_admin, ROLE_user]
  • The default converter used sub as the name, here a UUID, and produced one SCOPE_ authority per scope. The roles admin and user in realm_access were ignored.
  • The customised converter kept the scope authorities, added ROLE_admin and ROLE_user, and used preferred_username as the name, so Authentication.getName() returns ann.
  • The third converter reached the nested roles with the SpEL expression [realm_access][roles], evaluated against the claims map, and produced ROLE_admin and ROLE_user but no SCOPE_ authorities, because it replaces the scope converter instead of adding to it.
  • All three results include FACTOR_BEARER: Spring Security 7 records which kind of authentication produced the token, for its multi-factor authentication support.

Roles keep their case, so the rule is hasRole("admin"), not hasRole("ADMIN"); many teams upper-case them in the converter. To use the converter, declare it as a bean of type JwtAuthenticationConverter, which Spring Boot picks up, or pass it with jwt(jwt -> jwt.jwtAuthenticationConverter(converter)). Simple cases need no code at all. Spring Boot has the properties spring.security.oauth2.resourceserver.jwt.authorities-claim-name, authority-prefix and principal-claim-name, and Spring Boot 4.1 also has authorities-claim-expressions, which builds an ExpressionJwtGrantedAuthoritiesConverter like the third one from a list of expressions. Combining scopes with roles, as the second converter does, still needs code. Once authorities are mapped, @PreAuthorize("hasRole('admin')") works as on the method security page.

OIDC login for a web application

A web application that wants "log in with your company account" is an OAuth2 client. It uses the authorization code flow, a series of browser redirects. This program plays the browser with redirects turned off, so each hop is printed, together with what the stand-in provider receives:

Java
package demo.oauth2.login;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.CookieManager;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class OidcLogin {

    static final Set<String> RANDOM = Set.of("state", "nonce", "code_challenge", "code");

    /** A minimal OpenID provider that logs in "ann" without asking for a password. */
    static class Provider {
        final HttpServer server;
        final String issuer;
        final NimbusJwtEncoder signer;
        final String jwks;
        String nonce;

        Provider() throws Exception {
            RSAKey key = new RSAKeyGenerator(2048).keyID("idp-key").generate();
            signer = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));
            jwks = new JWKSet(key.toPublicJWK()).toString();
            server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
            issuer = "http://localhost:" + server.getAddress().getPort();
            server.createContext("/.well-known/openid-configuration", ex -> json(ex, "{"
                    + "\"issuer\":\"" + issuer + "\","
                    + "\"authorization_endpoint\":\"" + issuer + "/authorize\","
                    + "\"token_endpoint\":\"" + issuer + "/token\","
                    + "\"userinfo_endpoint\":\"" + issuer + "/userinfo\","
                    + "\"jwks_uri\":\"" + issuer + "/certs\","
                    + "\"response_types_supported\":[\"code\"],"
                    + "\"subject_types_supported\":[\"public\"],"
                    + "\"id_token_signing_alg_values_supported\":[\"RS256\"]}"));
            server.createContext("/authorize", this::authorize);
            server.createContext("/token", this::token);
            server.createContext("/userinfo", ex -> {
                System.out.println("    [provider] /userinfo, "
                        + ex.getRequestHeaders().getFirst("Authorization"));
                json(ex, "{\"sub\":\"ann-42\",\"name\":\"Ann Lee\","
                        + "\"email\":\"ann@example.com\"}");
            });
            server.createContext("/certs", ex -> json(ex, jwks));
            server.start();
        }

        void authorize(HttpExchange ex) throws IOException {
            Map<String, String> q = params(ex.getRequestURI().getRawQuery());
            System.out.println("    [provider] /authorize received:");
            q.forEach((k, v) -> System.out.println("      " + k + " = "
                    + (RANDOM.contains(k) ? "(random, " + v.length() + " chars)"
                                          : v.replaceAll("localhost:\\d+", "localhost:APP"))));
            nonce = q.get("nonce");
            ex.getResponseHeaders().add("Location", q.get("redirect_uri")
                    + "?code=one-time-code-123&state=" + q.get("state"));
            ex.sendResponseHeaders(302, -1);
            ex.close();
        }

        void token(HttpExchange ex) throws IOException {
            Map<String, String> form = params(new String(ex.getRequestBody().readAllBytes(),
                    StandardCharsets.UTF_8));
            System.out.println("    [provider] /token: grant_type = " + form.get("grant_type")
                    + ", code = " + form.get("code") + ", code_verifier sent = "
                    + form.containsKey("code_verifier") + ", client authenticated with "
                    + ex.getRequestHeaders().getFirst("Authorization").split(" ")[0]);
            Instant now = Instant.now();
            String idToken = signer.encode(JwtEncoderParameters.from(
                    JwsHeader.with(SignatureAlgorithm.RS256).keyId("idp-key").build(),
                    JwtClaimsSet.builder().issuer(issuer).subject("ann-42")
                            .audience(List.of("web-app")).claim("nonce", nonce)
                            .claim("name", "Ann Lee").issuedAt(now)
                            .expiresAt(now.plusSeconds(300)).build())).getTokenValue();
            json(ex, "{\"access_token\":\"opaque-access-token\",\"token_type\":\"Bearer\","
                    + "\"expires_in\":300,\"scope\":\"openid profile email\","
                    + "\"id_token\":\"" + idToken + "\"}");
        }

        static Map<String, String> params(String raw) {
            Map<String, String> map = new LinkedHashMap<>();
            for (String pair : raw.split("&")) {
                String[] kv = pair.split("=", 2);
                map.put(kv[0], URLDecoder.decode(kv[1], StandardCharsets.UTF_8));
            }
            return map;
        }

        static void json(HttpExchange ex, String body) throws IOException {
            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", "application/json");
            ex.sendResponseHeaders(200, bytes.length);
            ex.getResponseBody().write(bytes);
            ex.close();
        }
    }

    @RestController
    static class ProfileController {
        @GetMapping("/profile")
        String profile(@AuthenticationPrincipal OidcUser user) {
            return "Hello " + user.getFullName() + " <" + user.getEmail() + ">, subject "
                    + user.getSubject() + ", issuer is the provider: "
                    + user.getIdToken().getIssuer().toString().startsWith("http://localhost");
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(ProfileController.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .oauth2Login(Customizer.withDefaults());
            return http.build();
        }
    }

    public static void main(String[] args) throws Exception {
        Provider provider = new Provider();
        String reg = "spring.security.oauth2.client.registration.shop.";
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                reg + "client-id", "web-app",
                reg + "client-secret", "web-app-secret",
                reg + "scope", "openid,profile,email",
                "spring.security.oauth2.client.provider.shop.issuer-uri", provider.issuer));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            HttpClient browser = HttpClient.newBuilder().cookieHandler(new CookieManager())
                    .followRedirects(HttpClient.Redirect.NEVER).build();
            URI next = URI.create(base + "/profile");
            for (int hop = 1; next != null; hop++) {
                HttpResponse<String> r = browser.send(HttpRequest.newBuilder(next).build(),
                        HttpResponse.BodyHandlers.ofString());
                String who = next.getPort() == provider.server.getAddress().getPort()
                        ? "provider" : "app";
                System.out.println(hop + ". GET " + who + " " + next.getPath() + " -> "
                        + r.statusCode());
                next = r.headers().firstValue("Location").map(next::resolve).orElse(null);
                if (r.statusCode() == 200) {
                    System.out.println("   " + r.body());
                }
            }
        } finally {
            provider.server.stop(0);
        }
    }
}
Output
1. GET app /profile -> 302
2. GET app /oauth2/authorization/shop -> 302
    [provider] /authorize received:
      response_type = code
      client_id = web-app
      scope = openid profile email
      state = (random, 44 chars)
      redirect_uri = http://localhost:APP/login/oauth2/code/shop
      nonce = (random, 43 chars)
      code_challenge = (random, 43 chars)
      code_challenge_method = S256
3. GET provider /authorize -> 302
    [provider] /token: grant_type = authorization_code, code = one-time-code-123, code_verifier sent = true, client authenticated with Basic
    [provider] /userinfo, Bearer opaque-access-token
4. GET app /login/oauth2/code/shop -> 302
5. GET app /profile -> 200
   Hello Ann Lee <ann@example.com>, subject ann-42, issuer is the provider: true
  • Hop 1: /profile needs a login, so the app saved the request and redirected to /oauth2/authorization/shop, where shop is the registration id from the properties.
  • Hop 2: that endpoint redirected the browser to the provider's /authorize with response_type = code, the client id, the scopes, a redirect_uri, and four random values. state ties the response to this browser session, nonce ties the ID token to this request, and code_challenge with S256 is PKCE, which makes a stolen authorization code useless without the matching secret. Spring Security sent PKCE parameters although this client also has a client secret.
  • Hop 3: the stand-in logged the user in without a form and redirected back with a one-time code and the same state.
  • Hop 4: at /login/oauth2/code/shop, Spring checked state, then exchanged the code at /token server to server, authenticating with HTTP Basic (the client id and secret) and sending the code_verifier for PKCE. It verified the ID token's signature, issuer, audience and nonce, called /userinfo with the access token, and created a session.
  • Hop 5: the saved request ran. The OidcUser principal combined the ID token (name and subject) with the userinfo response (email).

The application needed only these properties, plus oauth2Login() in the chain:

YAML
spring:
  security:
    oauth2:
      client:
        registration:
          shop:
            client-id: web-app
            client-secret: ${SHOP_CLIENT_SECRET}
            scope: openid,profile,email
        provider:
          shop:
            issuer-uri: https://login.example.com/realms/shop

Unlike the resource server, the client reads the discovery document at startup, so the application does not start if the provider is unreachable. For Google, GitHub, Facebook and Okta, Spring Security has the provider details built in, and a registration named google needs only a client id and secret. The browser holds only a session cookie; the tokens stay on the server, in the OAuth2AuthorizedClientService, which is the safest place for them. For calling other APIs with the user's access token, the client side also offers OAuth2AuthorizedClientManager and RestClient integration.

Opaque tokens and introspection

Some providers issue opaque access tokens: random strings that mean nothing without asking the provider. The resource server checks them by calling the provider's introspection endpoint (RFC 7662). This program sends two requests with the same valid token and one with a revoked token, and counts the provider calls:

Java
package demo.oauth2.opaque;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class OpaqueTokens {

    static int introspections;

    /** The provider's introspection endpoint (RFC 7662). Only "tok-ann" is active. */
    static HttpServer startProvider() throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/introspect", OpaqueTokens::introspect);
        server.start();
        return server;
    }

    static void introspect(HttpExchange ex) throws IOException {
        introspections++;
        String form = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
        String token = form.replaceAll(".*token=([^&]*).*", "$1");
        System.out.println("    [provider] introspection #" + introspections + " for "
                + token);
        String body = token.equals("tok-ann")
                ? "{\"active\":true,\"sub\":\"ann\",\"scope\":\"orders.read\",\"exp\":"
                        + Instant.now().plusSeconds(300).getEpochSecond() + "}"
                : "{\"active\":false}";
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        ex.getResponseHeaders().add("Content-Type", "application/json");
        ex.sendResponseHeaders(200, bytes.length);
        ex.getResponseBody().write(bytes);
        ex.close();
    }

    @RestController
    static class OrderController {
        @GetMapping("/api/orders")
        String orders(Authentication auth) {
            return "orders of " + auth.getName() + " " + auth.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .filter(a -> a.startsWith("SCOPE_")).toList();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(OrderController.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/error").permitAll()
                            .anyRequest().hasAuthority("SCOPE_orders.read"))
                    .oauth2ResourceServer(rs -> rs.opaqueToken(Customizer.withDefaults()));
            return http.build();
        }
    }

    public static void main(String[] args) throws Exception {
        HttpServer provider = startProvider();
        String opaque = "spring.security.oauth2.resourceserver.opaquetoken.";
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                opaque + "introspection-uri",
                "http://localhost:" + provider.getAddress().getPort() + "/introspect",
                opaque + "client-id", "orders-api",
                opaque + "client-secret", "orders-api-secret"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            for (String token : new String[] {"tok-ann", "tok-ann", "tok-revoked"}) {
                HttpResponse<String> r = HttpClient.newHttpClient().send(
                        HttpRequest.newBuilder(URI.create(base + "/api/orders"))
                                .header("Authorization", "Bearer " + token).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("GET /api/orders with " + token + " -> " + r.statusCode()
                        + (r.statusCode() == 200 ? " " + r.body() : ""));
            }
            System.out.println("Introspection calls for 3 requests: " + introspections);
        } finally {
            provider.stop(0);
        }
    }
}
Output
[provider] introspection #1 for tok-ann
GET /api/orders with tok-ann -> 200 orders of ann [SCOPE_orders.read]
    [provider] introspection #2 for tok-ann
GET /api/orders with tok-ann -> 200 orders of ann [SCOPE_orders.read]
    [provider] introspection #3 for tok-revoked
GET /api/orders with tok-revoked -> 401
Introspection calls for 3 requests: 3
  • Each request triggered its own introspection call, 3 calls for 3 requests: Spring Security does not cache the answers.
  • For tok-ann, the provider answered active: true with the subject and scope, and the scope became SCOPE_orders.read as with JWTs.
  • tok-revoked got active: false, and the API returned 401.

That is the trade-off between the two token types. A JWT is checked locally with a cached key, so it costs no network call, but it stays valid until it expires. An opaque token is checked by the provider each time, so revoking it takes effect at once, but every API request waits for a call to the provider. If you need opaque tokens at high request rates, wrap the OpaqueTokenIntrospector in a short-lived cache. Spring Security 7.1 also adds RestClientOpaqueTokenIntrospector, built on RestClient.

Testing a resource server without a provider

Tests should not need a running identity provider or real signed tokens. spring-security-test has a MockMvc post-processor, jwt(), that puts a ready-made JWT authentication on the request and skips decoding. This program runs four requests against the same rules as before:

Java
package demo.oauth2.testing;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.BadJwtException;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;

public class TestWithMockJwt {

    @RestController
    static class OrderController {
        @GetMapping("/api/orders")
        String list(@AuthenticationPrincipal Jwt jwt) {
            return "orders of " + jwt.getSubject();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(OrderController.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .anyRequest().hasAuthority("SCOPE_orders.read"))
                    .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()));
            return http.build();
        }

        @Bean
        JwtDecoder jwtDecoder() {       // never called: jwt() below skips decoding
            return token -> {
                throw new BadJwtException("real tokens are not used in this test");
            };
        }
    }

    /** A short name for the post-processor that puts a mock JWT on a request. */
    static SecurityMockMvcRequestPostProcessors.JwtRequestPostProcessor jwt() {
        return SecurityMockMvcRequestPostProcessors.jwt();
    }

    static void perform(MockMvc mvc, String label, RequestBuilder request) throws Exception {
        MockHttpServletResponse r = mvc.perform(request).andReturn().getResponse();
        System.out.println(label + " -> " + r.getStatus()
                + (r.getStatus() == 200 ? " " + r.getContentAsString() : ""));
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            MockMvc mvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) context)
                    .apply(SecurityMockMvcConfigurers.springSecurity()).build();

            perform(mvc, "no token", get("/api/orders"));
            perform(mvc, "jwt() with its defaults", get("/api/orders").with(jwt()));
            perform(mvc, "jwt() with SCOPE_orders.read", get("/api/orders").with(jwt()
                    .authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))));
            perform(mvc, "jwt() with subject bob and scope claim", get("/api/orders").with(jwt()
                    .jwt(j -> j.subject("bob").claim("scope", "orders.read"))));
        }
    }
}
Output
no token -> 401
jwt() with its defaults -> 403
jwt() with SCOPE_orders.read -> 200 orders of user
jwt() with subject bob and scope claim -> 200 orders of bob
  • With no token, the request got 401, exactly as in production.
  • jwt() with its defaults got 403: the mock token's subject is user and its scope is read, so the authority is SCOPE_read, not SCOPE_orders.read.
  • authorities(...) set the authority directly and got 200, orders of user.
  • jwt(j -> j.subject("bob").claim("scope", "orders.read")) changed the claims instead, and the application's converter derived the authority from them. Testing through the claims also tests your converter, which the authorities(...) form skips.

The program builds MockMvc by hand so that it can run as a plain main; in a JUnit test the same calls follow @SpringBootTest and @AutoConfigureMockMvc. The decoder bean is a stub that always fails, which proves that jwt() never calls it. For WebFlux, SecurityMockServerConfigurers.mockJwt() does the same with WebTestClient, as on the reactive security page.

Choosing a setup

OAuth2 setups and when to use each
SituationSetup
API called with tokens from an OIDC providerResource server with issuer-uri and audiences
Provider without discovery, or a fixed keyjwk-set-uri or public-key-location, plus an explicit issuer check
Roles in a custom claimA JwtAuthenticationConverter bean, or the authorities-claim-name property for top-level claims
Tokens must be revocable at onceOpaque tokens with introspection, ideally with a short cache
Server-rendered web app with company loginoauth2Login() with a registration and issuer-uri
Single-page appA backend that does oauth2Login() and keeps the tokens (the backend-for-frontend pattern), or PKCE in the browser with a public client
Service-to-service callsThe client credentials grant through OAuth2AuthorizedClientManager
Your application issues its own tokensSpring Authorization Server, or the simpler setup on the JWT refresh token page

Let the provider own passwords and logins, and keep your applications to checking tokens and mapping claims. For the filter chain that all of this plugs into, see Spring Security in Spring Boot.