Skip to content

Grokem · https://www.grokem.com/programming/web-development/backend/spring-security-jwt-cheat-sheet-secure-a-spring-boot-rest-api-with-method-rules

BackendReference

Spring Security JWT cheat sheet: secure a Spring Boot REST API with method rules

A compact reference for protecting a Spring Boot REST API with JWT Bearer tokens and @PreAuthorize method rules. It lists the dependencies, properties, annotations, defaults and common errors in tables.

Pankaj Nigam

Technical Writer

Published Updated
  • 7 min read
  • 0 sec

Tested with
  • Spring Framework7.0.10
  • Spring Security7.0.10
  • Spring Boot
  • OAuth 2.0
  • Maven
Your progress
  1. Spring Security JWT cheat sheet: secure a Spring Boot REST API with method rules7 min(finished)
    0%

Use this page as a lookup. Your API acts as an OAuth 2.0 resource server: it reads Authorization: Bearer tokens, validates the JWT, and turns scopes into authorities. Method rules such as @PreAuthorize then decide who may call each method.

Versions: Spring Security builds against Spring Framework 7.0.10. Spring Boot manages the Spring Security version through its BOM, so you do not set a version on the starters.

Out of scope: issuing JWTs. Your API only validates tokens from an authorization server. For a custom token, read the official OAuth2 Resource Server pages listed in the references.

Artifacts at a glance

Need Artifact Why
Default web security spring-boot-starter-security Aggregates the Spring Security dependencies for Boot
JWT resource server spring-boot-starter-oauth2-resource-server Boot starter for the resource server feature set
Resource server core spring-security-oauth2-resource-server Bearer token support
JWT decoding and checks spring-security-oauth2-jose Needed together with the module above for JWT Bearer tokens

Boot's BOM supplies versions, so leave <version> out. You also need a web starter for your REST controllers. Spring Initializr adds it for you.

xml
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
  </dependency>
</dependencies>

Configuration: point to the authorization server

Property Value Effect
spring.security.oauth2.resourceserver.jwt.issuer-uri The iss claim value of your tokens Resource Server discovers public keys and validates incoming JWTs

The authorization server must support one of these endpoints under the issuer: /.well-known/openid-configuration, or the openid-configuration/issuer or oauth-authorization-server/issuer variants.

Discovery runs at the first request that carries a JWT. Startup does not depend on the authorization server being available.

yaml
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://idp.example.com/issuer

Security configuration class

With issuer-uri set, Boot already configures a JWT resource server that requires authentication for every request. Add this class to make the rules visible and to switch on method security.

Element Role
@EnableWebSecurity Activates web security configuration
@EnableMethodSecurity Activates @PreAuthorize and related annotations. Boot does not do this by default
authorizeHttpRequests Request-level rules, here anyRequest().authenticated()
oauth2ResourceServer with jwt Enables JWT Bearer token authentication

A SecurityFilterChain bean replaces Boot's default web security settings.

java
package com.example.api;

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

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authorize) -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer((oauth2) -> oauth2
                .jwt(Customizer.withDefaults())
            );
        return http.build();
    }
}

Request flow for a JWT

ClientAuthorization: BearerAuthentication filterBearerTokenAuthenticationTokenProviderManagerJwtAuthenticationProviderJwtAuthenticationToken@PreAuthorize checkREST controller403 AccessDeniedExceptionJwtDecoderJwtAuthenticationConverter
How a Bearer token becomes an authenticated call that method rules then check.
Stage Component What happens
1 Authentication filter Reads Authorization: Bearer, builds a BearerTokenAuthenticationToken
2 ProviderManager Hands the token to its AuthenticationProvider
3 JwtAuthenticationProvider Uses JwtDecoder to decode, verify and validate the Jwt
4 JwtAuthenticationConverter Converts the Jwt into granted authorities
5 Result A JwtAuthenticationToken

Checks on a well-formed JWT: signature (against the key from jwks_url), the exp and nbf timestamps, and the iss claim.

Item Default
Scope mapping Each scope becomes an authority with the prefix SCOPE_
Authentication#getPrincipal A Spring Security Jwt object
Authentication#getName The JWT sub property, if present
Key rotation Automatic when the authorization server publishes new keys

Method rules cheat sheet

Annotation Runs Use for
@PreAuthorize Before the method Checks authorities or parameters
@PostAuthorize After the method Checks the return value, via returnObject
@PreFilter Before the method Filters input collections
@PostFilter After the method Filters returned collections

Expressions from the official examples:

Expression Meaning
hasAuthority('permission:read') Caller holds that authority
returnObject.owner == authentication.name Returned object belongs to the caller
hasAuthority('SCOPE_reports.read') Caller's token has scope reports.read (SCOPE_ prefix)

Rules:

  • Annotate any Spring-managed class or method.
  • Several annotations on one method run in series.
  • A denied call throws AccessDeniedException. ExceptionTranslationFilter turns it into a 403 response.
  • Outside an HTTP request, you must handle AccessDeniedException yourself.
java
@Service
public class MyCustomerService {

    @PreAuthorize("hasAuthority('permission:read')")
    @PostAuthorize("returnObject.owner == authentication.name")
    public Customer readCustomer(String id) { ... }
}

Protected endpoint example

Replace reports.read with a scope your authorization server issues. The method needs the authority SCOPE_reports.read.

java
package com.example.api;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ReportController {

    @GetMapping("/reports")
    @PreAuthorize("hasAuthority('SCOPE_reports.read')")
    public String list(Authentication authentication) {
        return "reports for " + authentication.getName();
    }
}
bash
curl -i http://localhost:8080/reports \
  -H "Authorization: Bearer YOUR_JWT"

Boot defaults and switches

Behaviour Detail
Spring Security on classpath Web applications are secured by default, including /error
Default user Name user, random password printed at WARN level at startup. For development only
Change default user spring.security.user.name and spring.security.user.password
Turn off default web security Add a SecurityFilterChain bean
Turn off default UserDetailsService Add a UserDetailsService, AuthenticationProvider or AuthenticationManager bean
Automatic back-off UserDetailsService auto-configuration backs off when spring-security-oauth2-resource-server is on the classpath
Actuator and static rules EndpointRequest and PathRequest build request matchers

Opaque tokens use an OpaqueTokenIntrospector instead of a JwtDecoder. See the OAuth2 page for those properties.


From Grokem: https://www.grokem.com/programming/web-development/backend/spring-security-jwt-cheat-sheet-secure-a-spring-boot-rest-api-with-method-rules

Finished this article?

How did this strike you?

Be the first to react – it is anonymous.

Community

Questions about this?

Ask in Questions and help and get help from other readers.

Ask a questionBrowse Questions and help

Comments

No comments yet. Share what worked for you, or ask a question.

Keep learning

Picked for this article

Related reading, discussions and learning paths on the same subject.

All in Backend

Learning paths

Learning pathIntermediate

Building and calling APIs

Design an HTTP API people can rely on, read its status codes, choose between REST, GraphQL and gRPC, receive webhooks safely and call a paginated API with retries.

5 lessonsabout 50 minStart

Choose what we may use. You can change this at any time with “Privacy choices” at the foot of every page. Details are in the Cookie policy and the Privacy policy.

Strictly necessary

Remembers your theme, the lessons you marked as done and this choice. It stays on your device, tracks nothing and cannot be switched off.

Always on
What exactly is collected, and why

Google Analytics

Collects
The pages you view, your device and browser type, your language, how you reached the site and your approximate location (country and city, worked out from your IP address).
Why
To understand which pages and lessons are used, so we can improve them.
Stored
Two cookies, _ga and _ga_<id>, for up to 2 years. Google acts for us; the data is processed by Google, including outside your country.

Grokem’s own counts

Collects
The pages you open and how long you stay, how far you scroll, where you came from, your device type, browser, screen size, language and time zone. Your IP address is turned into a code that changes every day; it is never stored as it is.
Why
To see how long lessons are read and where readers leave. Not shared with anyone.
Stored
A random visitor ID, a visit ID and the time of your last page view in your browser’s storage (gr_vid, gr_sid, gr_last). No name or email is attached.