OAuth2 Resource Server with JWT in Spring Security
An OAuth2 resource server is an API that accepts access tokens issued by a separate authorization server, such as Keycloak, Okta, Microsoft Entra ID, Auth0 or Spring Authorization Server. The API never sees passwords. It only checks that each request carries a valid token from the issuer it trusts, and that the token grants the permissions the endpoint needs.
Spring Security turns a Spring Boot application into a resource server with one dependency, one property and one line of configuration. This tutorial explains what happens behind that line, then runs a shipments API against a real local authorization server, using two client applications with different scopes.
1. What Is an OAuth2 Resource Server?
In OAuth2, the resource server is the role that hosts protected data. Clients obtain access tokens from the authorization server and present them as Authorization: Bearer <token>. When the tokens are JWTs, the resource server can validate them locally: it downloads the issuer's public keys once (its JWK Set) and checks every token's signature, expiry and issuer itself.
In Spring Security this is oauth2ResourceServer(oauth2 -> oauth2.jwt(...)). Unlike self-issued JWT authentication, your application holds no private key and has no login endpoint; issuing tokens is entirely the authorization server's job. The difference between the framework and the token format is covered in OAuth2 vs JWT.
2. Why Use a Resource Server?
- Central identity. Users, passwords, MFA and client registrations live in one place; dozens of APIs simply trust its tokens.
- Scoped access. Each client receives only the scopes it needs, such as read-only access for a tracking widget.
- No shared secrets. APIs need only the issuer's public keys, which are published and rotated by the issuer.
- Standard behaviour. Error responses follow RFC 6750, so clients and gateways understand them.
3. How Token Validation Works
- Spring Boot reads
spring.security.oauth2.resourceserver.jwt.issuer-uriand, on first use, fetches the issuer's metadata to find itsjwks_uri. BearerTokenAuthenticationFiltertakes the token from theAuthorizationheader.JwtDecoderverifies the signature with the cached public keys and checksexp,nbfand thatissequals the configured issuer. Keys are refreshed automatically when the issuer rotates them.JwtAuthenticationConvertermaps each value of thescope(orscp) claim to an authority prefixed withSCOPE_.- Authorization rules such as
hasAuthority("SCOPE_shipments.write")decide; failures return 401 (invalid_token) or 403 (insufficient_scope).
4. A Complete Example: Shipments API Behind an Authorization Server
A logistics company has a public tracking widget that may only read shipments, and an internal dispatch service that may also create them. Both are machine clients using the client credentials grant. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.
4.1 A Local Authorization Server for Testing
Any OAuth2 or OIDC provider works. For a self-contained test, Spring Boot can run Spring Authorization Server from properties alone. Create a separate Spring Boot application with the spring-boot-starter-security-oauth2-authorization-server dependency, an ordinary @SpringBootApplication main class, and this configuration:
server:
port: 9000
spring:
security:
oauth2:
authorizationserver:
issuer: http://localhost:9000
client:
tracking-widget:
registration:
client-id: tracking-widget
client-secret: "{noop}widget-secret" # demo only; store hashed secrets in production
client-authentication-methods: client_secret_basic
authorization-grant-types: client_credentials
scopes: shipments.read
dispatch-service:
registration:
client-id: dispatch-service
client-secret: "{noop}dispatch-secret"
client-authentication-methods: client_secret_basic
authorization-grant-types: client_credentials
scopes: shipments.read,shipments.write
package com.javabytechie.authserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class, args);
}
}
4.2 The Resource Server
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9000 # must match the "iss" claim exactly
package com.javabytechie.shipments;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.requestMatchers(HttpMethod.GET, "/api/shipments/**").hasAuthority("SCOPE_shipments.read")
.requestMatchers(HttpMethod.POST, "/api/shipments").hasAuthority("SCOPE_shipments.write")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}
package com.javabytechie.shipments;
import java.util.Map;
import org.springframework.http.HttpStatus;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ShipmentController {
@GetMapping("/api/whoami")
public Map<String, Object> whoami(@AuthenticationPrincipal Jwt jwt) {
return Map.of("sub", jwt.getSubject(), "iss", jwt.getIssuer().toString(),
"scope", jwt.getClaimAsStringList("scope"));
}
@GetMapping("/api/shipments/{id}")
public Map<String, String> shipment(@PathVariable String id) {
return Map.of("id", id, "status", "IN_TRANSIT", "lastScan", "Hyderabad hub");
}
@PostMapping("/api/shipments")
@ResponseStatus(HttpStatus.CREATED)
public Map<String, String> create(@RequestBody Map<String, String> body, @AuthenticationPrincipal Jwt jwt) {
return Map.of("id", "SH-302", "destination", body.get("destination"), "createdBy", jwt.getSubject());
}
}
package com.javabytechie.shipments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ShipmentsApplication {
public static void main(String[] args) {
SpringApplication.run(ShipmentsApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- One property.
issuer-uriis all Spring Boot needs to build aJwtDecoder. It discovers the key URL and validatesissagainst this exact value, so a trailing slash or a different host name makes every token fail. - One line of DSL.
oauth2ResourceServer(oauth2 -> oauth2.jwt(...))adds the bearer token filter and the JWT authentication provider. - Scope rules. The token's
scopeclaim becomesSCOPE_shipments.readand so on, which the URL rules check per HTTP method. - No CSRF setting. The resource server support ignores CSRF for requests that carry a bearer token, so the
POSTworks without disabling CSRF globally. - The
Jwtprincipal.@AuthenticationPrincipal Jwtgives controllers the validated claims, such as the client ID insub.
6. Expected Output
With both applications running, the widget obtains a token from the authorization server and calls the API; then the dispatch service does the same with the write scope:
$ curl -s -u tracking-widget:widget-secret -d grant_type=client_credentials -d scope=shipments.read localhost:9000/oauth2/token | jq '{token_type, expires_in, scope}'
{
"token_type": "Bearer",
"expires_in": 299,
"scope": "shipments.read"
}
$ WIDGET_TOKEN=$(curl -s -u tracking-widget:widget-secret -d grant_type=client_credentials -d scope="shipments.read" localhost:9000/oauth2/token | jq -r .access_token)
$ curl -H "Authorization: Bearer $WIDGET_TOKEN" localhost:8080/api/whoami
HTTP/1.1 200
{"scope":["shipments.read"],"iss":"http://localhost:9000","sub":"tracking-widget"}
$ curl -H "Authorization: Bearer $WIDGET_TOKEN" localhost:8080/api/shipments/SH-301
HTTP/1.1 200
{"lastScan":"Hyderabad hub","status":"IN_TRANSIT","id":"SH-301"}
$ curl -H "Authorization: Bearer $WIDGET_TOKEN" -X POST localhost:8080/api/shipments -H 'Content-Type: application/json' -d '{"destination":"Nagpur"}'
HTTP/1.1 403
WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
$ DISPATCH_TOKEN=$(curl -s -u dispatch-service:dispatch-secret -d grant_type=client_credentials -d scope="shipments.read shipments.write" localhost:9000/oauth2/token | jq -r .access_token)
$ curl -H "Authorization: Bearer $DISPATCH_TOKEN" -X POST localhost:8080/api/shipments -H 'Content-Type: application/json' -d '{"destination":"Nagpur"}'
HTTP/1.1 201
{"destination":"Nagpur","createdBy":"dispatch-service","id":"SH-302"}
$ curl -s localhost:8080/.well-known/oauth-protected-resource | jq .
{
"resource": "http://localhost:8080",
"bearer_methods_supported": [
"header"
],
"tls_client_certificate_bound_access_tokens": true
}
The token endpoint returned a five-minute bearer token with the requested scope. The API recognised the widget as the subject, with the issuer it trusts. Reading a shipment works, but creating one returns 403 with error="insufficient_scope", because the widget only has shipments.read. The dispatch service's token carries both scopes and creates the shipment. Finally, the API publishes its own OAuth 2.0 Protected Resource Metadata (RFC 9728), which Spring Security 7 serves automatically and advertises in its 401 challenges.
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| No passwords or signing keys in the API | Depends on a correctly configured external authorization server |
| Local validation: no call to the issuer per request | Revoked tokens stay valid until they expire (use short lifetimes, or opaque tokens) |
| Automatic key discovery and rotation through JWK Sets | Issuer URLs must match exactly, which trips up containerised setups |
| Fine-grained scopes per client | Scopes describe client permissions, not user ownership; combine with method security for data rules |
8. Common Mistakes and Best Practices
- Issuer mismatch. Inside Docker the API may reach the issuer as
http://auth:9000while tokens sayhttp://localhost:9000. Make the configured issuer equal theissclaim, or configurejwk-set-uriplus an explicit issuer validator. - Forgetting the audience. When one issuer serves many APIs, set
spring.security.oauth2.resourceserver.jwt.audiencesso tokens meant for another API are rejected. - Using
hasRolefor scopes. Scopes becomeSCOPE_xauthorities; usehasAuthority("SCOPE_x")or map claims with a customJwtAuthenticationConverter. - Plain-text client secrets.
{noop}is for local tests only. Real authorization servers store hashed secrets or use private-key client authentication. - Long token lifetimes. Keep access tokens short; clients can request new ones cheaply.
9. Summary
- A resource server accepts bearer tokens issued by a separate authorization server.
- In Spring Boot, set
issuer-uriand calloauth2ResourceServer(o -> o.jwt(...)). - Keys are discovered from the issuer and cached; signature, expiry and issuer are checked on every request.
- The
scopeclaim becomesSCOPE_authorities for URL and method rules. - Invalid tokens get 401
invalid_token; valid tokens without the scope get 403insufficient_scope.
10. References
Frequently Asked Questions (FAQ)
Q1. What does issuer-uri do in a Spring Boot resource server?
It tells Spring Boot where the authorization server is. Spring Security reads the issuer's metadata to find its public keys and requires every token's iss claim to equal this value.
Q2. What is the difference between issuer-uri and jwk-set-uri?
jwk-set-uri points directly at the public keys and skips discovery. issuer-uri discovers the keys and also validates the issuer claim. With jwk-set-uri alone, add issuer validation yourself.
Q3. Why do scopes appear as SCOPE_ authorities?
The default JwtAuthenticationConverter maps each value of the scope or scp claim to an authority with the SCOPE_ prefix, so rules use hasAuthority("SCOPE_read").
Q4. Does a resource server call the authorization server on every request?
No, not for JWTs. It caches the issuer's public keys and validates tokens locally. Opaque tokens, in contrast, require an introspection call.
Q5. Do I need to disable CSRF for a resource server?
No. Spring Security ignores CSRF for requests that carry a bearer token, because browsers do not attach such tokens automatically.