Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Configure a Spring Boot service as an OAuth2 resource server that accepts JWTs from https://idp.example.com/realms/shop, only accepts tokens with audience orders-api, and maps the "roles" claim to ROLE_ authorities.

We add spring-boot-starter-oauth2-resource-server and set spring.security.oauth2.resourceserver.jwt.issuer-uri to https://idp.example.com/realms/shop; Boot uses it to discover the signing keys and validates iss, exp and nbf. The audience is not checked by default, so we set the audiences property to orders-api in recent Boot or add a JwtClaimValidator for aud. For roles, we configure a JwtAuthenticationConverter whose JwtGrantedAuthoritiesConverter reads the roles claim with the ROLE_ prefix, and enable it with oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())).

Why this question is asked

Turning a Spring Boot service into an OAuth2 resource server takes only a few lines, which is exactly why it is often done incompletely. The defaults validate the signature and lifetime, but not whether the token was meant for this API, and they ignore role claims. Interviewers ask this coding question to see whether we know which checks happen by default and which we must add. In this answer, we will add the dependency and issuer, see what Boot validates, add the audience check two ways, map the roles claim, wire the filter chain, and look at the startup trade-off between issuer-uri and jwk-set-uri.

1The Dependency and the Issuer

A resource server is an API that accepts access tokens. Spring Boot's resource server starter brings Spring Security's JWT support and the Nimbus library that parses and verifies JWTs.

XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
# application.yml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com/realms/shop

From the issuer URI, Boot reads the provider's discovery document (for this Keycloak-style URL, /.well-known/openid-configuration under the realm), finds the jwks_uri where the public signing keys are published, and creates a JwtDecoder. For every request with an Authorization: Bearer header, the decoder verifies the signature with those keys and runs the default validators: the iss claim must equal the issuer URI exactly, the token must not be expired (exp) and must already be valid (nbf), with a small clock skew allowance of 60 seconds by default.

2Adding the Audience Check

Notice what is missing: aud. By default, any token signed by this realm passes, including tokens issued for other APIs or clients in the same realm. We want only tokens meant for orders-api. Recent Spring Boot versions have a property for it.

YAML
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://idp.example.com/realms/shop
audiences: orders-api
# token aud=["orders-api"] -> accepted
# token aud=["billing-api"] -> 401, WWW-Authenticate: Bearer error="invalid_token"
# token without aud -> 401
Step throughHow an incoming JWT is checked
  1. Read Bearer tokenAuthorization header
  2. Signature valid with JWKS key?
    YesRun validatorsNo401 invalid_token
  3. iss, exp, nbf valid?default validators
    YesCheck audienceNo401 invalid_token
  4. aud contains orders-api?only if configured
    YesConvert to authoritiesNo401 invalid_token
  5. Authorization ruleshasRole, hasAuthority

5 steps in order. Play them, or step through them one at a time.

Without that property, or when we need full control, we build the decoder ourselves and add a JwtClaimValidator next to the default validators.

3The Audience Check in Java

This version works on every Spring Security 6 and 7 release and makes the validators explicit.

Java
@Bean
JwtDecoder jwtDecoder() {
String issuer = "https://idp.example.com/realms/shop";
NimbusJwtDecoder decoder = JwtDecoders.fromIssuerLocation(issuer); // discovery + JWKS
OAuth2TokenValidator<Jwt> audience = new JwtClaimValidator<List<String>>(
JwtClaimNames.AUD, aud -> aud != null && aud.contains("orders-api"));
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
JwtValidators.createDefaultWithIssuer(issuer), // iss, exp, nbf
audience)); // aud
return decoder;
}

The important detail is createDefaultWithIssuer. Calling setJwtValidator replaces the validators, so if we passed only the audience validator, we would silently lose the issuer and expiry checks. Delegating to both keeps everything. When we declare our own JwtDecoder bean, Boot's issuer and audiences properties for the decoder no longer apply, so we configure it fully here.

4Mapping the roles Claim to ROLE_ Authorities

The default converter turns the scope or scp claim into SCOPE_ authorities and ignores roles. We configure it to read roles with the ROLE_ prefix, so hasRole("ADMIN") works for a token with "roles": ["ADMIN"].

Java
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
roles.setAuthoritiesClaimName("roles");
roles.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(roles);
return converter;
}
// token: {"sub":"anne","aud":["orders-api"],"roles":["ADMIN","USER"]}
// authorities: [ROLE_ADMIN, ROLE_USER]

Recent Boot versions offer properties for this simple case, authorities-claim-name and authority-prefix under spring.security.oauth2.resourceserver.jwt; check your version. One practical note for Keycloak: by default it puts realm roles in a nested realm_access.roles claim and may set aud to account, so either add protocol mappers for a top-level roles claim and an orders-api audience, or write a converter that reads the nested map. Replacing the converter also drops SCOPE_ authorities; if the API checks scopes too, combine both lists.

5Wiring It Into the Filter Chain

Finally, we enable bearer token authentication in the SecurityFilterChain. Customizer.withDefaults() picks up our JwtDecoder and JwtAuthenticationConverter beans, or Boot's auto-configured decoder.

Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(a -> a
.requestMatchers(HttpMethod.DELETE, "/orders/**").hasRole("ADMIN")
.requestMatchers("/orders/**").hasRole("USER")
.anyRequest().denyAll())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(c -> c.disable()); // no cookies: bearer tokens only
return http.build();
}
// DELETE /orders/7 with roles ["USER"] -> 403
// DELETE /orders/7 with roles ["ADMIN"] -> 204
// GET /orders without a token -> 401

Disabling CSRF is reasonable here only because the API authenticates exclusively with bearer tokens, which browsers do not attach automatically; if the same chain also accepted session cookies, CSRF protection would be needed.

6Issuer-uri Versus jwk-set-uri

Discovery from issuer-uri is convenient, but it means the service must reach the identity provider to learn its keys. Recent Boot versions resolve the discovery document lazily on the first request rather than at startup; check your version. Either way, an identity provider outage during a deployment can delay or fail the first requests.

Setting jwk-set-uri directly, for example https://idp.example.com/realms/shop/protocol/openid-connect/certs, skips the discovery call: the service only fetches keys, and caches them. If we set both jwk-set-uri and issuer-uri, Boot uses the key set URI for keys and still validates the issuer. In larger platforms that is a sensible default, because it removes one dependency on the identity provider being reachable at the moment our service starts.

7Follow-up questions

How do I test that a token for another audience is rejected?

The jwt() request post-processor in spring-security-test bypasses the decoder, so it cannot test audience validation. We unit test the decoder's validator with Jwt objects built in the test, or run an integration test with a local key pair and a JWKS served by a mock server, signing tokens with different aud values.

What happens when the identity provider rotates its signing key?

The new key appears in the JWKS with a new kid. When a token arrives with an unknown kid, the Nimbus decoder fetches the key set again, so rotation works without a restart as long as the provider publishes the new key before using it.

Why does iss have to match exactly?

Because it is compared as a string. https://idp.example.com/realms/shop and the same URL with a trailing slash are different issuers, and a mismatch causes every token to be rejected. Copy the issuer value from the discovery document.

8Conclusion

In this answer, we configured a resource server with spring-boot-starter-oauth2-resource-server and issuer-uri, which discovers the JWKS and validates signature, iss, exp and nbf. We added the missing audience check with the audiences property or a JwtClaimValidator combined with the default validators, mapped the roles claim to ROLE_ authorities with a JwtAuthenticationConverter, enabled oauth2ResourceServer with jwt defaults in the filter chain, and saw how jwk-set-uri reduces the dependency on discovery.

What to say in the interviewAbout 70 seconds aloud

Open with

I would add spring-boot-starter-oauth2-resource-server and set spring.security.oauth2.resourceserver.jwt.issuer-uri to https://idp.example.com/realms/shop. Boot reads the discovery document from that issuer, finds the JWKS URI, and builds a JwtDecoder that verifies the signature and checks iss, exp and nbf.

Then, if they want more

The audience is not checked by default, so any token from that realm would pass. In recent Boot versions I set the audiences property to orders-api; otherwise I define my own NimbusJwtDecoder and set a DelegatingOAuth2TokenValidator with JwtValidators.createDefaultWithIssuer plus a JwtClaimValidator that requires aud to contain orders-api, being careful not to replace the default validators.

For roles, I define a JwtAuthenticationConverter whose JwtGrantedAuthoritiesConverter has authorities claim name roles and prefix ROLE_, so hasRole ADMIN works; recent Boot also has properties for that, and with Keycloak I would check whether roles are nested under realm_access. In the SecurityFilterChain I add oauth2ResourceServer with jwt and Customizer.withDefaults, authorization rules ending in denyAll, and a stateless session.

Finally, issuer-uri means calling the identity provider for discovery, so in production I often set jwk-set-uri as well, which avoids depending on discovery while still validating the issuer.

About this answer

Last updated
12 November 2026
Versions it names
Spring Security 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Configure a Spring Boot service as an OAuth2 resource server that accepts JWTs from...": https://scrivio-interview-library.netlify.app/spring-boot/oauth2-and-oidc/929d2f0bd0/