Sub topic 6
Turning a Spring Boot app into a resource server
This chapter assumes you know basic Spring Boot and Spring MVC, HTTP headers and status codes, and the difference between authentication and authorization. You need Java 17 or later and Maven or Gradle. By the end you will have a working resource server that accepts JWT bearer tokens.
What the starter does for you
A resource server is an API that accepts access tokens issued by an authorization server. It does not log users in. It only checks that each request carries a token it trusts, then decides what the caller may do.
Spring Security provides this with the spring-boot-starter-oauth2-resource-server dependency. Adding it brings in the resource server support, the Nimbus library used to parse and verify JWTs, and Spring Boot's auto-configuration for them.
For Maven, add this to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>For Gradle, the equivalent lines are:
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-web'The starter pulls in spring-security-oauth2-resource-server, spring-security-oauth2-jose, and spring-boot-starter-security. You do not need to add those separately.
Pointing the app at the issuer
The smallest working configuration is one property. Set issuer-uri to the base URL of your authorization server:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://issuer.example.com/realms/demoAt startup, Spring Boot uses this value to do three things:
- It requests the provider's metadata from
<issuer-uri>/.well-known/openid-configuration. Providers that only implement OAuth2 authorization server metadata are tried at the/.well-known/oauth-authorization-serverpath. - It reads the
jwks_urifield from that metadata and builds a decoder that downloads the signing keys from there. - It adds a check that the
issclaim of every incoming token equals the configured issuer.
Your app therefore never stores a key. It trusts whatever keys the issuer publishes.
The tutorial covers the decoder in the next chapter. For now, treat it as the component that turns a raw token string into a verified Jwt object.
How a request flows through the app
Once the starter is on the classpath, Spring Boot adds a BearerTokenAuthenticationFilter to the security filter chain. This filter reads the Authorization header, hands the token to an authentication provider, and stores the result in the security context.
Two outcomes matter here. A missing, malformed, expired, or badly signed token leads to 401. A valid token that lacks the needed authority leads to 403. The auth errors chapter covers this in detail.
Writing the SecurityFilterChain
Spring Boot's default security configuration protects every endpoint. It does so with a form login and a session, which suits a browser application. An API needs a different setup, so you define your own SecurityFilterChain bean:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
}Each part of the chain has a purpose:
| Part | Effect |
|---|---|
| `authorizeHttpRequests` | Declares which requests are open and which need authentication or an authority. |
| `requestMatchers("/public/**").permitAll()` | Lets anyone through, with or without a token. |
| `hasAuthority("SCOPE_admin")` | Requires the authority `SCOPE_admin`, which comes from the token's `scope` claim. |
| `anyRequest().authenticated()` | Requires a valid token for everything else. |
| `sessionCreationPolicy(STATELESS)` | Stops Spring Security from creating or using an HTTP session. |
| `oauth2ResourceServer(... jwt(...))` | Turns on bearer token handling and selects JWT validation. |
| `@EnableMethodSecurity` | Enables `@PreAuthorize` and related annotations. A later chapter uses it. |
Rules are evaluated in order, and the first match wins. Put specific matchers before general ones, and keep anyRequest() last. Spring Security rejects a configuration where a rule follows anyRequest().
Why the chain is stateless
A bearer token is sent with every request, so the server has no need to remember the caller between requests. Disabling sessions avoids creating a JSESSIONID cookie and removes a second way to authenticate. It also means a request cannot become authenticated from a stale session instead of a token.
CSRF and form login
When you configure oauth2ResourceServer, you do not enable formLogin or httpBasic, so those mechanisms stay off in your own chain. CSRF protection stays on by default. For a pure bearer-token API with no cookies, CSRF attacks do not apply, because the browser does not attach the token automatically. Many teams therefore disable it:
http.csrf(csrf -> csrf.disable());Do this only if the API never authenticates by cookie. If you also serve a browser session on the same app, keep CSRF on.
Trying it out
Add a small controller to see the result:
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class MeController {
@GetMapping("/me")
Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
return Map.of("sub", jwt.getSubject(), "issuer", jwt.getIssuer().toString());
}
}Start the app, then call it without a token:
curl -i http://localhost:8080/meExpect a 401 response with a WWW-Authenticate: Bearer header. Now call it with a token from your issuer:
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/meA valid token returns 200 and a JSON body with the subject and issuer. If you call /admin/anything with a token that lacks the admin scope, you get 403.
Choosing between issuer-uri and jwk-set-uri
You can configure the key source in two ways.
| Property | What Spring does | When to use it |
|---|---|---|
| `issuer-uri` | Discovers metadata, finds the JWK set, validates `iss`. | The provider supports discovery. This is the default choice. |
| `jwk-set-uri` | Downloads keys directly from the given URL. Does not validate `iss` by default. | The provider has no discovery endpoint, or you do not want a startup call to the issuer. |
If you use jwk-set-uri, you can also set issuer-uri to get issuer validation without discovery. Spring Boot then only checks the iss claim and does not contact the issuer. This setup is common when the app cannot reach the issuer's discovery URL at startup:
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: https://issuer.example.com/realms/demo/protocol/openid-connect/certs
issuer-uri: https://issuer.example.com/realms/demoCommon errors
- Every request returns 401 with a valid token. The token's
issdiffers fromissuer-uri. Compare them character by character. A trailing slash is enough to break the match. 403where you expected200. The authority name is wrong. The default converter producesSCOPE_plus each value in thescopeclaim, so a scope calledadminbecomesSCOPE_admin, notROLE_admin.- The app fails to start with a connection error. The
issuer-uriis unreachable from where the app runs. Fix the network path or switch tojwk-set-uriwithissuer-uri. - A session cookie appears in responses. A custom filter chain is missing the stateless policy, or another chain is matching the request.
- Public endpoints return 401 when a bad token is sent. The bearer filter runs before authorization. An invalid token on a
permitAll()path is still rejected, because the filter tries to authenticate it first. Send no token to such paths.
Recap
The starter adds the filter and decoder support. The issuer-uri property gives the app a key source and an issuer check. A SecurityFilterChain bean defines which endpoints need which authorities and turns off sessions. The next chapter looks at the JwtDecoder itself and how to customize it.
Exercise
A resource server is configured with only jwk-set-uri. A token signed by one of the published keys but issued by a different, unrelated issuer arrives. Is it accepted, and what single property addition fixes this?
Show answer
It is accepted, because with only jwk-set-uri Spring checks the signature and timestamps but does not compare iss to any expected value. Adding spring.security.oauth2.resourceserver.jwt.issuer-uri makes Spring validate the iss claim without contacting the issuer for discovery.
Exercise
Your chain has .anyRequest().authenticated() followed by .requestMatchers("/admin/**").hasAuthority("SCOPE_admin"). What happens, and how do you fix it?
Show answer
Spring Security rejects this configuration, because no rule may come after anyRequest(). Rules are matched in order and the first match wins. Move the /admin/** matcher above anyRequest() and keep anyRequest() last.