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:
| Token | Format | Audience | Used for |
|---|---|---|---|
| Access token | Usually a JWT; sometimes opaque | The API (resource server) | Authorization: Bearer |
| ID token (OIDC) | Always a JWT | The client | Telling the client who logged in; never sent to APIs |
| Refresh token | Opaque | The authorization server | Getting new access tokens without a new login |
In Spring Boot 4 the two roles have separate starters: spring-boot-starter-security-oauth2-resource-serverspring-boot-starter-security-oauth2-clientspring-boot-starter-oauth2-resource-serverspring-boot-starter-oauth2-clientspring.security.oauth2
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-uriaudiences
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);
}
}
}
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
, found the/.well-known/openid-configuration in it, and fetched the public keys fromjwks_uri . Later calls used the cached keys and caused no provider traffic./certs - A valid token with the scope
was accepted, and the controller readorders.read from thesub principal:Jwt .orders of ann - The same token on
got 403 withPOST : the signature was fine, but the rule wantserror="insufficient_scope" . The resource server turns each space-separated value ofSCOPE_orders.write into ascope authority.SCOPE_ - A token whose
isaud got 401billing-api , because of theThe aud claim is not valid property. Without that check, a token issued for any application of the same provider would be accepted by this API.audiences - Tokens from another issuer, or expired ones, got 401 with
and the reason.invalid_token
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
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://login.example.com/realms/shop
audiences: orders-api
Use jwk-set-uriissuer-uripublic-key-locationjwk-set-uri
Mapping claims to roles and user names
Providers put roles in different claims: Keycloak uses realm_access.rolesrolesscopescp
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);
}
}
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
as the name, here a UUID, and produced onesub authority per scope. The rolesSCOPE_ andadmin inuser were ignored.realm_access - The customised converter kept the scope authorities, added
andROLE_admin , and usedROLE_user as the name, sopreferred_username returnsAuthentication.getName() .ann - The third converter reached the nested roles with the SpEL expression
, evaluated against the claims map, and produced[realm_access][roles] andROLE_admin but noROLE_user authorities, because it replaces the scope converter instead of adding to it.SCOPE_ - All three results include
: Spring Security 7 records which kind of authentication produced the token, for its multi-factor authentication support.FACTOR_BEARER
Roles keep their case, so the rule is hasRole("admin")hasRole("ADMIN")JwtAuthenticationConverterjwt(jwt -> jwt.jwtAuthenticationConverter(converter))spring.security.oauth2.resourceserver.jwt.authorities-claim-nameauthority-prefixprincipal-claim-nameauthorities-claim-expressionsExpressionJwtGrantedAuthoritiesConverter@PreAuthorize("hasRole('admin')")
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:
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);
}
}
}
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:
needs a login, so the app saved the request and redirected to/profile , where/oauth2/authorization/shop is the registration id from the properties.shop - Hop 2: that endpoint redirected the browser to the provider's
with/authorize , the client id, the scopes, aresponse_type = code , and four random values.redirect_uri ties the response to this browser session,state ties the ID token to this request, andnonce withcode_challenge 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.S256 - Hop 3: the stand-in logged the user in without a form and redirected back with a one-time
and the samecode .state - Hop 4: at
, Spring checked/login/oauth2/code/shop , then exchanged the code atstate server to server, authenticating with HTTP Basic (the client id and secret) and sending the/token for PKCE. It verified the ID token's signature, issuer, audience andcode_verifier , callednonce with the access token, and created a session./userinfo - Hop 5: the saved request ran. The
principal combined the ID token (name and subject) with the userinfo response (email).OidcUser
The application needed only these properties, plus oauth2Login()
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 googleOAuth2AuthorizedClientServiceOAuth2AuthorizedClientManagerRestClient
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:
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);
}
}
}
[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
, the provider answeredtok-ann with the subject and scope, and the scope becameactive: true as with JWTs.SCOPE_orders.read gottok-revoked , and the API returned 401.active: false
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 OpaqueTokenIntrospectorRestClientOpaqueTokenIntrospectorRestClient
Testing a resource server without a provider
Tests should not need a running identity provider or real signed tokens. spring-security-testjwt()
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"))));
}
}
}
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.
with its defaults got 403: the mock token's subject isjwt() and its scope isuser , so the authority isread , notSCOPE_read .SCOPE_orders.read set the authority directly and got 200,authorities(...) .orders of user changed the claims instead, and the application's converter derived the authority from them. Testing through the claims also tests your converter, which thejwt(j -> j.subject("bob").claim("scope", "orders.read")) form skips.authorities(...)
The program builds MockMvc by hand so that it can run as a plain main@SpringBootTest@AutoConfigureMockMvcjwt()SecurityMockServerConfigurers.mockJwt()WebTestClient
Choosing a setup
| Situation | Setup |
|---|---|
| API called with tokens from an OIDC provider | Resource server with issuer-uriaudiences |
| Provider without discovery, or a fixed key | jwk-set-uripublic-key-location |
| Roles in a custom claim | A JwtAuthenticationConverterauthorities-claim-name |
| Tokens must be revocable at once | Opaque tokens with introspection, ideally with a short cache |
| Server-rendered web app with company login | oauth2Login()issuer-uri |
| Single-page app | A backend that does oauth2Login() |
| Service-to-service calls | The client credentials grant through OAuth2AuthorizedClientManager |
| Your application issues its own tokens | Spring Authorization Server, or the simpler setup on the |
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