Sub topic 14
Opaque tokens and introspection as an alternative
This chapter assumes you have the JWT resource server from the earlier chapters. That means a SecurityFilterChain, an understanding of SCOPE_ authorities, and the 401 and 403 behavior. Here you swap local JWT validation for remote validation and see what changes.
What an opaque token is
An opaque token is a bearer token whose contents mean nothing to the API that receives it. It is usually a random string such as mF_9.B5f-4.1JqM. It has no header, payload, or signature that the resource server can read. All the information about the token (who it belongs to, what it allows, when it expires) is stored at the authorization server.
A JWT is self-contained, so the resource server can validate it alone with a cached public key. An opaque token is a reference. To validate it, the resource server must ask the authorization server. That request is called token introspection, and it is defined in RFC 7662.
How introspection works
The resource server sends the token to the introspection endpoint using HTTP POST. It authenticates itself with client credentials, usually HTTP Basic. The authorization server replies with JSON.
{
"active": true,
"sub": "alice",
"scope": "orders.read orders.write",
"aud": ["orders-api"],
"iss": "https://issuer.example.com/realms/demo",
"exp": 1796117000
}The active field is the only required one. If it is false, the token is expired, revoked, or unknown, and the response carries no other detail. If it is true, the other fields describe the token. Spring Security turns them into an OAuth2AuthenticatedPrincipal with the attributes as claims.
Configuring the resource server
Opaque token support needs an extra library on the classpath. Spring Security uses the Nimbus OAuth 2.0 SDK to build and parse the introspection call. With the starter already in place, add this dependency:
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
<version>${nimbus-oauth2-oidc-sdk.version}</version>
<scope>runtime</scope>
</dependency>Spring Boot's dependency management normally supplies the version. If your build does not manage it, set the property or write a version number yourself.
Next, add the properties. The client secret comes from the environment, not from the file.
spring:
security:
oauth2:
resourceserver:
opaquetoken:
introspection-uri: https://issuer.example.com/oauth2/introspect
client-id: orders-api
client-secret: ${INTROSPECTION_CLIENT_SECRET}
# In the filter chain:
# .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults()))Then switch the filter chain from jwt(...) to opaqueToken(...).
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class OpaqueSecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults()));
return http.build();
}
}Everything after authentication stays the same. The scope attribute is split on spaces and mapped to SCOPE_ authorities, just as with JWTs. Request rules and @PreAuthorize("hasAuthority('SCOPE_orders.read')") work without changes.
One difference affects controllers. The principal is no longer a Jwt. Inject an OAuth2AuthenticatedPrincipal instead.
@RestController
class MeController {
@GetMapping("/me")
Map<String, Object> me(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
return Map.of("sub", String.valueOf(principal.getAttribute("sub")),
"name", principal.getName());
}
}Where the checks happen
With a JWT, Spring Security checks the signature, timestamps, issuer, and (if you add it) the audience. With an opaque token, the authorization server decides whether the token is active. The default introspector only trusts that answer. It does not re-check iss or aud on its own.
If your API must accept tokens meant only for it, check the audience yourself. Wrap the default introspector and reject tokens that fail.
import java.util.List;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.oauth2.server.resource.introspection.SpringOpaqueTokenIntrospector;
class AudienceCheckingIntrospector implements OpaqueTokenIntrospector {
private final OpaqueTokenIntrospector delegate;
AudienceCheckingIntrospector(OpaqueTokenIntrospector delegate) {
this.delegate = delegate;
}
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {
OAuth2AuthenticatedPrincipal principal = delegate.introspect(token);
List<String> audience = principal.getAttribute("aud");
if (audience == null || !audience.contains("orders-api")) {
throw new BadOpaqueTokenException("Token audience does not include orders-api");
}
return principal;
}
}Register it as a bean. Spring Security uses an OpaqueTokenIntrospector bean in place of the one Boot builds from properties.
@Bean
OpaqueTokenIntrospector introspector(
@Value("${spring.security.oauth2.resourceserver.opaquetoken.introspection-uri}") String uri,
@Value("${spring.security.oauth2.resourceserver.opaquetoken.client-id}") String clientId,
@Value("${spring.security.oauth2.resourceserver.opaquetoken.client-secret}") String secret) {
return new AudienceCheckingIntrospector(new SpringOpaqueTokenIntrospector(uri, clientId, secret));
}A BadOpaqueTokenException produces a 401 with WWW-Authenticate: Bearer error="invalid_token", the same as an invalid JWT. If the introspection endpoint itself is unreachable, the resulting exception is not a bad-token error. That case surfaces as a server-side failure, which is not a 401. Monitor it separately.
JWT or opaque: the trade-offs
| Concern | JWT (local validation) | Opaque (introspection) |
|---|---|---|
| Latency per request | No network call after the key is cached | One HTTP call per request unless cached |
| Revocation | Not seen until `exp` | Visible on the next introspection |
| Load on authorization server | Low, fetches keys only | Scales with API traffic |
| Availability dependency | Needs keys only | Needs the endpoint on every request |
| Information exposed to clients | Claims are readable by anyone holding the token | Nothing readable |
| Token size | Large | Small |
Revocation is the main reason to choose opaque tokens. A revoked JWT stays valid until it expires, because no resource server asks anyone. An opaque token stops working as soon as the authorization server says active: false.
The price is coupling. Every API request depends on the authorization server being fast and available. You can reduce the load by caching introspection results for a short period, such as 30 to 60 seconds. A cache puts back a small version of the JWT problem, because a revoked token still works until its cache entry expires. Choose the cache lifetime as the revocation delay you can tolerate.
Mixing token types
A single oauth2ResourceServer configuration accepts either jwt or opaqueToken, not both. The two are mutually exclusive in one chain, and configuring both causes a startup error. If one API must accept both formats, supply an AuthenticationManagerResolver<HttpServletRequest>. It picks a JWT or opaque authentication manager per request, for example by tenant or by path. This is also the usual approach during a migration from one format to the other. In many setups, two filter chains matched by path are simpler.
Testing
spring-security-test has an opaqueToken() post-processor that matches the jwt() one. It builds an authenticated principal without calling any introspection endpoint.
// import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.opaqueToken;
@Test
void ordersAllowedWithScope() throws Exception {
mockMvc.perform(get("/orders")
.with(opaqueToken().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))))
.andExpect(status().isOk());
}
@Test
void ordersRequiresToken() throws Exception {
mockMvc.perform(get("/orders"))
.andExpect(status().isUnauthorized());
}These tests check your authorization rules. They do not check that the real authorization server is configured correctly. For that, run an integration test against a test instance of your provider, or a stub server such as WireMock that returns introspection JSON.
Common errors
- The app fails at startup or at the first request with a missing class from
com.nimbusds. Theoauth2-oidc-sdkdependency is absent. - Every request returns 401 although the token is valid. The introspection client credentials are wrong, or the client is not allowed to call the endpoint. Check the authorization server's logs.
- Scopes are missing. Some servers return
scopeas an array or put roles under another attribute. Supply your own introspector that builds the authorities. - Latency spikes under load. Each request waits on the introspection call. Add a bounded cache or move to JWTs.
Exercise
Your API handles payment approvals, and security requires that a revoked token stop working within seconds. The authorization server can handle the extra traffic. Would you pick JWTs or opaque tokens with introspection, and what would you do about caching?
Show answer
Pick opaque tokens with introspection. A JWT stays valid until exp and the resource server never asks whether it was revoked. Introspection reports active: false right after revocation. If you cache results to cut load, keep the cache lifetime at or below the acceptable revocation delay, for example a few seconds, and cache only active responses.
Exercise
You switched oauth2ResourceServer from jwt(...) to opaqueToken(...). @PreAuthorize("hasAuthority('SCOPE_orders.read')") still works, but a controller method with @AuthenticationPrincipal Jwt jwt now receives null. Why, and how do you fix it?
Show answer
With opaque tokens the principal is an OAuth2AuthenticatedPrincipal, not a Jwt, so the Jwt parameter cannot be resolved and is null. Change the parameter type to OAuth2AuthenticatedPrincipal and read values with getAttribute("sub") or getName(). Authorization still works because the scope attribute is mapped to SCOPE_ authorities.