00:00

OAuth2 Resource Server with JWT in Spring Security

Last updated:

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

Resource server validating a JWTAt startup or first use, the resource server reads the issuer metadata from issuer-uri and finds the jwks_uri. For each request, BearerTokenAuthenticationFilter extracts the token, JwtDecoder verifies signature, exp and iss using the cached keys, and JwtAuthenticationConverter turns the scope claim into SCOPE_ authorities for the authorization rules. issuer-uri http://localhost:9000 Discovery (once) issuer metadata, then jwks_uri Authorization server publishes public keys Bearer token on every request JwtDecoder signature, exp, iss SCOPE_ authorities checked by your rules cached keys
Figure 1: the issuer's keys are discovered once; every request is validated locally against them.
  1. Spring Boot reads spring.security.oauth2.resourceserver.jwt.issuer-uri and, on first use, fetches the issuer's metadata to find its jwks_uri.
  2. BearerTokenAuthenticationFilter takes the token from the Authorization header.
  3. JwtDecoder verifies the signature with the cached public keys and checks exp, nbf and that iss equals the configured issuer. Keys are refreshed automatically when the issuer rotates them.
  4. JwtAuthenticationConverter maps each value of the scope (or scp) claim to an authority prefixed with SCOPE_.
  5. 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:

authorization server: application.yml
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
AuthServerApplication.java
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

5. Step-by-Step Code Explanation

  1. One property. issuer-uri is all Spring Boot needs to build a JwtDecoder. It discovers the key URL and validates iss against this exact value, so a trailing slash or a different host name makes every token fail.
  2. One line of DSL. oauth2ResourceServer(oauth2 -> oauth2.jwt(...)) adds the bearer token filter and the JWT authentication provider.
  3. Scope rules. The token's scope claim becomes SCOPE_shipments.read and so on, which the URL rules check per HTTP method.
  4. No CSRF setting. The resource server support ignores CSRF for requests that carry a bearer token, so the POST works without disabling CSRF globally.
  5. The Jwt principal. @AuthenticationPrincipal Jwt gives controllers the validated claims, such as the client ID in sub.

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:

Terminal
$ 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

AdvantagesLimitations
No passwords or signing keys in the APIDepends on a correctly configured external authorization server
Local validation: no call to the issuer per requestRevoked tokens stay valid until they expire (use short lifetimes, or opaque tokens)
Automatic key discovery and rotation through JWK SetsIssuer URLs must match exactly, which trips up containerised setups
Fine-grained scopes per clientScopes 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:9000 while tokens say http://localhost:9000. Make the configured issuer equal the iss claim, or configure jwk-set-uri plus an explicit issuer validator.
  • Forgetting the audience. When one issuer serves many APIs, set spring.security.oauth2.resourceserver.jwt.audiences so tokens meant for another API are rejected.
  • Using hasRole for scopes. Scopes become SCOPE_x authorities; use hasAuthority("SCOPE_x") or map claims with a custom JwtAuthenticationConverter.
  • 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-uri and call oauth2ResourceServer(o -> o.jwt(...)).
  • Keys are discovered from the issuer and cached; signature, expiry and issuer are checked on every request.
  • The scope claim becomes SCOPE_ authorities for URL and method rules.
  • Invalid tokens get 401 invalid_token; valid tokens without the scope get 403 insufficient_scope.

10. References