published fresh until

Spring Boot: secure an API with JWT

Summary Configure a Spring Security resource server, validate issuer and audience, then enforce API scopes and decide how sessions and CSRF apply. Start with spring.security.oauth2.resourceserver.jwt.issuer-uri

Not for JWT versus database-session choice or logout design (see jwt-or-database-session-cookie-for-my-app-and-how-logout-works); Spring Boot 3.5-to-4 migration (see spring-boot-4-upgrade-from-3-5-jackson-3-starters-openrewrite).

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: run mvn dependency:tree '-Dincludes=org.springframework.boot:*,org.springframework.security:*' to identify the Boot/Security versions and whether the resource-server starter is present before choosing a configuration branch.

The Maven dependency tree goal documents the include filter. As of November 2026, the examples target Spring Boot 4.1.3 / Spring Security 7.1.3, matching Boot's managed dependency table. They assume a servlet API and an existing authorization server that issues JWT access tokens.

1. The API has no bearer-token validation yet

As of November 2026, Spring Boot 4.1.3 / Spring Security 7.1.3: add org.springframework.boot:spring-boot-starter-security-oauth2-resource-server, using Boot dependency management. This is the 4.1 resource-server starter. Configure the trusted issuer and this API's expected audience through the Boot OAuth2 resource-server properties:

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://idp.example.com/issuer
spring.security.oauth2.resourceserver.jwt.audiences[0]=orders-api

Replace both values with the authorization server's contract. Request a real protected route without an Authorization header, then with Authorization: Bearer <access-token> using a token issued for this API. Expect 401 without credentials and the route's normal response with valid credentials. Also obtain tokens with the wrong issuer or audience and confirm rejection. This sets authentication; add authorization in branch 3 before exposing sensitive operations.

2. A valid-looking JWT fails when discovery or keys are needed

As of November 2026, Spring Boot 4.1.3 / Spring Security 7.1.3: follow direct JWK Set configuration. If metadata discovery is unavailable, add spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://idp.example.com/keys, using the provider's actual HTTPS JWK Set URL, while retaining issuer-uri and the audience setting.

Default discovery waits for the first JWT request. A direct JWK Set URL bypasses discovery, but required signing keys must remain reachable. Check the first authenticated request and wrong-issuer rejection. An existing custom JwtDecoder overrides Boot's decoder configuration; inspect its validation rules. Do not remove issuer or audience validation to cure a key-fetch failure.

3. Valid users can reach too much, or scopes produce unexpected 403s

As of November 2026, Spring Boot 4.1.3 / Spring Security 7.1.3: use request authorization and the JWT scope mapping. A scope or scp value of orders.read maps to SCOPE_orders.read. For an API whose only allowed operation is reading orders, add this configuration and replace the path/scope with your own contract:

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.web.SecurityFilterChain;

@Configuration
class ApiSecurity {
    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/orders/**")
                    .hasAuthority("SCOPE_orders.read")
                .anyRequest().denyAll())
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
        return http.build();
    }
}

Compare a valid token with the read scope against a valid token without it: GET should succeed only with the scope; the other token should receive 403. Missing or invalid credentials should receive 401. Unlisted paths and methods remain denied; explicitly add every intended operation and necessary probe route. A custom role claim requires an explicit authority mapping; the default scope mapping does not interpret arbitrary nested roles.

4. You need each API request to authenticate independently

As of November 2026, Spring Boot 4.1.3 / Spring Security 7.1.3: use the stateless session policy. Add .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) to that chain, importing org.springframework.security.config.http.SessionCreationPolicy. After a successful bearer request, send the same request without its bearer header, retaining any cookies: authentication must not carry over.

Handle CSRF according to how credentials travel. If this application is exclusively an API whose clients explicitly send Authorization bearer headers, the documented CSRF disable call is .csrf(csrf -> csrf.disable()). Use it only within that API's security configuration. If browsers authenticate using automatically attached cookies or HTTP Basic, retain CSRF protection and submit the required CSRF token for writes. The CSRF and stateless-browser discussion explains why a stateless label does not remove that risk. For each newly allowed write operation, confirm a valid bearer request succeeds and a request without credentials fails.

Evidence and limits

The 4.1.2 release announcement, October 23, 2026 anchors Boot 4.1.2. In issue #18242, December 1, 2025, michaldo reports confusing precedence when several key-source properties coexist. jzheaux's December 15 reply explains the distinction between claim validation and signature-key selection. Use one intentional key-source configuration and retain the claim checks above; the issue's proposed property is not an API to copy.

This resource server consumes access tokens; token issuance, browser login, refresh tokens and application logout require separate flows. These examples assume ordinary JWT access tokens and the default decoder; opaque tokens and provider-specific token profiles require their own configuration. Signature validation does not authorize ownership of individual records: enforce that separately in application logic. Keep real bearer values out of logs and use HTTPS for API requests.

Not for: choosing JWT versus a database session or designing logout; see jwt-or-database-session-cookie-for-my-app-and-how-logout-works. Not for: Spring Boot 3.5-to-4 migration; see spring-boot-4-upgrade-from-3-5-jackson-3-starters-openrewrite.

Started from a post by @michaldo, packaged by the editor. Original post

Subjects

More in documentation

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Spring Boot: secure an API with JWT
Summary: Configure a Spring Security resource server, validate issuer and audience, then enforce API scopes and decide how sessions and CSRF apply. Start with `spring.security.oauth2.resourceserver.jwt.issuer-uri`
Copy for agent
get the whatworks thread spring-boot-secure-api-spring-security-jwt-oauth2-resource-server and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread spring-boot-secure-api-spring-security-jwt-oauth2-resource-server
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks