Skip to main content

Web frameworks · Advanced · 30 min

Protect a Spring Boot API with Spring Security

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Eclipse Temurin JDK 25 · Spring Boot 4.1.2 · Spring Security 7.1.2

You will lock down a Spring Boot 4.1 notes API with Spring Security 7 so that it accepts only signed JWTs from your issuer, turns scopes and roles into authorities, guards methods with @PreAuthorize, and proves each rule with tests.

On this page

An API that trusts a token without checking it properly is worse than one with no login at all, because it looks safe. Spring Security does the checking for you, but only once you tell it what a good token looks like: which key signed it, who issued it, who it is for, and what it allows.

In this tutorial you secure a small notes API. You start with Spring Boot's locked-by-default behaviour, then write your own SecurityFilterChain that keeps one route public and makes the rest of the API an OAuth 2.0 resource server. The API accepts JSON Web Tokens (JWTs) signed with RS256. In production an identity provider such as Keycloak, Auth0 or Entra ID signs them. Here, a short Java tool stands in for one, so nothing depends on an outside service. You then turn the token's scopes and roles into Spring authorities, guard individual methods with @PreAuthorize, send the API a set of bad tokens to see each one rejected for its own reason, and finish with tests written with spring-security-test.

Step 1 · Generate the project

Make a throwaway folder and ask start.spring.io for a Maven project with three dependencies: Spring Web, Spring Security, and OAuth2 Resource Server. The archive comes back over HTTPS and unpacks in place:

Bash
java -version
mkdir -p ~/spring-security-demo
cd ~/spring-security-demo
curl -fsS https://start.spring.io/starter.tgz \
  -d type=maven-project -d bootVersion=4.1.2 -d javaVersion=25 \
  -d groupId=dev.example -d artifactId=notes-api -d name=notes-api \
  -d packageName=dev.example.notes \
  -d dependencies=web,security,oauth2-resource-server | tar -xzf -
ls

The project comes with mvnw, the Maven wrapper. It downloads the exact Maven version the project expects the first time you run it, so you do not install Maven yourself.

Open pom.xml. Spring Boot 4 splits its starters into smaller modules, so you see spring-boot-starter-webmvc, spring-boot-starter-security and spring-boot-starter-security-oauth2-resource-server, plus test starters for each. The two security test starters bring in spring-security-test, which you use in the last steps. The parent, spring-boot-starter-parent 4.1.2, pins Spring Security to 7.1.2.

Check it worked

java -version reports version 25. ls lists HELP.md, mvnw, mvnw.cmd, pom.xml and src.

Step 2 · Add endpoints and see them locked

Create a controller with a public status route and three routes for notes. The notes live in memory, which keeps the focus on security:

Bash
cat > src/main/java/dev/example/notes/NotesController.java <<'JAVA'
package dev.example.notes;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
class NotesController {

    record Note(long id, String text, String author) {}
    record NewNote(String text) {}

    private final Map<Long, Note> notes = new ConcurrentSkipListMap<>();
    private final AtomicLong ids = new AtomicLong();

    NotesController() {
        save("Review who can delete notes", "system");
    }

    @GetMapping("/status")
    Map<String, String> status() {
        return Map.of("status", "ok");
    }

    @GetMapping("/notes")
    Collection<Note> list() {
        return notes.values();
    }

    @PostMapping("/notes")
    @ResponseStatus(HttpStatus.CREATED)
    Note create(@RequestBody NewNote body) {
        return save(body.text(), "anonymous");
    }

    @DeleteMapping("/notes/{id}")
    ResponseEntity<Void> delete(@PathVariable long id) {
        return notes.remove(id) == null
            ? ResponseEntity.notFound().build()
            : ResponseEntity.noContent().build();
    }

    private Note save(String text, String author) {
        Note note = new Note(ids.incrementAndGet(), text, author);
        notes.put(note.id(), note);
        return note;
    }
}
JAVA

Start the API in your second terminal, from ~/spring-security-demo. The first run downloads Maven and the project's dependencies, which takes a few minutes; later runs start in seconds:

Bash
./mvnw spring-boot:run

With Spring Security on the classpath and no configuration of your own, Spring Boot protects every route with its default chain, which asks for HTTP Basic or a login form. Boot normally also creates a development user with a generated password, but it backs off when the OAuth2 Resource Server library is present, because it expects tokens to replace passwords. So for now nobody can sign in at all. Ask for the status route, which you meant to be public:

Bash
curl -i http://localhost:8080/api/status

Check it worked

The response is HTTP/1.1 401, with a header WWW-Authenticate: Basic realm="Realm" and no body. Opening http://localhost:8080/login in a browser shows Spring's default sign-in form, but no user exists to sign in with. You replace this whole arrangement next.

Step 3 · Make a signing key and a token tool

A resource server never creates tokens. It checks tokens an authorisation server created, using that server's public key. To practise without one, write a small tool that does the authorisation server's part: it makes an RSA key pair and signs tokens with the private key. It uses only the JDK, and Java 25 runs a single source file directly, so there is nothing to build:

Bash
mkdir -p tools
cat > tools/Token.java <<'JAVA'
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// A local stand-in for an identity provider. It makes RSA keys and signs
// RS256 tokens for development only. Never deploy it next to the API.
public class Token {
    static final Base64.Encoder URL = Base64.getUrlEncoder().withoutPadding();

    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            System.err.println("usage: keygen <dir> | mint [name=value ...] | decode <token>");
            System.exit(2);
        }
        switch (args[0]) {
            case "keygen" -> keygen(Path.of(args.length > 1 ? args[1] : "keys"));
            case "mint" -> System.out.println(mint(options(args)));
            case "decode" -> decode(args[1]);
            default -> throw new IllegalArgumentException("unknown command " + args[0]);
        }
    }

    static void keygen(Path dir) throws Exception {
        Files.createDirectories(dir);
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        KeyPair pair = generator.generateKeyPair();
        Path privateFile = dir.resolve("private.pem");
        // Create the private key file readable by you only, then write to it.
        Files.createFile(privateFile, PosixFilePermissions.asFileAttribute(
                PosixFilePermissions.fromString("rw-------")));
        Files.writeString(privateFile, pem("PRIVATE KEY", pair.getPrivate().getEncoded()));
        Files.writeString(dir.resolve("public.pem"), pem("PUBLIC KEY", pair.getPublic().getEncoded()));
        System.out.println("wrote " + privateFile + " and " + dir.resolve("public.pem"));
    }

    static Map<String, String> options(String[] args) {
        Map<String, String> o = new HashMap<>(Map.of(
                "key", "keys/private.pem", "sub", "ada", "iss", "https://auth.example.test",
                "aud", "notes-api", "scope", "", "roles", "", "ttl", "600", "age", "0"));
        for (int i = 1; i < args.length; i++) {
            String[] kv = args[i].split("=", 2);
            o.put(kv[0], kv.length > 1 ? kv[1] : "");
        }
        return o;
    }

    static String mint(Map<String, String> o) throws Exception {
        long issuedAt = Instant.now().getEpochSecond() - Long.parseLong(o.get("age"));
        long expiresAt = issuedAt + Long.parseLong(o.get("ttl"));
        String roles = Stream.of(o.get("roles").split(" "))
                .filter(r -> !r.isBlank()).map(r -> "\"" + r + "\"")
                .collect(Collectors.joining(",", "[", "]"));
        String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
        String payload = "{\"iss\":\"" + o.get("iss") + "\",\"sub\":\"" + o.get("sub")
                + "\",\"aud\":\"" + o.get("aud") + "\",\"scope\":\"" + o.get("scope")
                + "\",\"roles\":" + roles + ",\"iat\":" + issuedAt + ",\"exp\":" + expiresAt + "}";
        String signingInput = URL.encodeToString(header.getBytes(StandardCharsets.UTF_8))
                + "." + URL.encodeToString(payload.getBytes(StandardCharsets.UTF_8));
        Signature rsa = Signature.getInstance("SHA256withRSA");
        rsa.initSign(readPrivateKey(Path.of(o.get("key"))));
        rsa.update(signingInput.getBytes(StandardCharsets.US_ASCII));
        return signingInput + "." + URL.encodeToString(rsa.sign());
    }

    static void decode(String token) {
        String[] parts = token.split("\\.");
        Base64.Decoder d = Base64.getUrlDecoder();
        System.out.println(new String(d.decode(parts[0]), StandardCharsets.UTF_8));
        System.out.println(new String(d.decode(parts[1]), StandardCharsets.UTF_8));
    }

    static PrivateKey readPrivateKey(Path file) throws Exception {
        String body = Files.readString(file).replaceAll("-----[A-Z ]+-----", "").replaceAll("\\s", "");
        return KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(body)));
    }

    static String pem(String type, byte[] der) {
        String b64 = Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der);
        return "-----BEGIN " + type + "-----\n" + b64 + "\n-----END " + type + "-----\n";
    }
}
JAVA
java tools/Token.java keygen keys
echo "keys/" >> .gitignore

The private key is created with permissions rw------- before anything is written to it, so no other user on the machine can read it even for a moment. The .gitignore line keeps the keys folder out of version control. Treat private.pem like a password: anyone who has it can mint tokens your API accepts.

Mint a token that may read notes, and look inside it:

Bash
TOKEN=$(java tools/Token.java mint scope="notes:read")
java tools/Token.java decode "$TOKEN"

Check it worked

keygen prints wrote keys/private.pem and keys/public.pem, and ls -l keys shows private.pem as -rw-------. decode prints two JSON objects: the header {"alg":"RS256","typ":"JWT"} and the claims, with "iss":"https://auth.example.test", "sub":"ada", "aud":"notes-api", "scope":"notes:read" and iat/exp timestamps ten minutes apart. No key was needed to read them. A JWT is signed, not encrypted, so never put anything in one that the holder should not see.

Step 4 · Write a SecurityFilterChain that accepts JWTs

Now replace Boot's defaults with your own rules. A SecurityFilterChain bean says which requests need what. A JwtDecoder bean says how to check a token. Defining your own SecurityFilterChain replaces Boot's default chain, so the login form and HTTP Basic go away.

Tell the API where the public key is and which issuer and audience to expect. Append three settings to application.properties:

Bash
cat >> src/main/resources/application.properties <<'PROPS'
notes.jwt.public-key-location=file:keys/public.pem
notes.jwt.issuer=https://auth.example.test
notes.jwt.audience=notes-api
PROPS

Then write the configuration:

Bash
cat > src/main/java/dev/example/notes/SecurityConfig.java <<'JAVA'
package dev.example.notes;

import java.security.interfaces.RSAPublicKey;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
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.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
class SecurityConfig {

    @Bean
    SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/status").permitAll()
                .anyRequest().authenticated())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
        return http.build();
    }

    @Bean
    JwtDecoder jwtDecoder(
            @Value("${notes.jwt.public-key-location}") RSAPublicKey publicKey,
            @Value("${notes.jwt.issuer}") String issuer,
            @Value("${notes.jwt.audience}") String audience) {
        NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey)
            .signatureAlgorithm(SignatureAlgorithm.RS256)
            .build();
        OAuth2TokenValidator<Jwt> audienceCheck = new JwtClaimValidator<List<String>>(
            JwtClaimNames.AUD, aud -> aud != null && aud.contains(audience));
        decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
            JwtValidators.createDefaultWithIssuer(issuer), audienceCheck));
        return decoder;
    }
}
JAVA

Read it in two halves.

  • apiSecurity lets anyone GET /api/status and requires an authenticated caller for everything else. Rules are checked top to bottom and the first match wins, so put specific rules first and anyRequest() last. STATELESS stops Spring creating an HTTP session: every request must bring its own token. oauth2ResourceServer(...jwt...) adds the filter that reads Authorization: Bearer <token> headers and passes the token to your decoder.
  • jwtDecoder checks the signature against your public key and accepts RS256 only, so a token that claims any other algorithm is refused. createDefaultWithIssuer checks exp and nbf (with 60 seconds of allowed clock difference) and requires iss to equal your issuer. The JwtClaimValidator adds the audience check that the defaults leave out: a token minted for another API in your company must not work here. Spring Security converts the notes.jwt.public-key-location text into an RSAPublicKey for you.

With a real identity provider you would not load a key file. You would build the decoder with NimbusJwtDecoder.withIssuerLocation(...) or withJwkSetUri(...), which fetch the provider's published keys and pick up new keys when it rotates them. The validators stay the same.

Stop the API in the second terminal with Ctrl+C and start it again with ./mvnw spring-boot:run, so it loads the new configuration.

Try the three kinds of request:

Bash
curl -s http://localhost:8080/api/status; echo
curl -i http://localhost:8080/api/notes
TOKEN=$(java tools/Token.java mint scope="notes:read")
curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/notes; echo

Check it worked

The status route answers {"status":"ok"} with no credentials, and /login no longer serves a form: it answers 401 like any other protected route. The notes route without a token answers HTTP/1.1 401 with a WWW-Authenticate: Bearer header; Spring Security 7 adds a resource_metadata link to it, which points clients to a description of this API (RFC 9728). With the token, the notes route answers [{"id":1,"text":"Review who can delete notes","author":"system"}].

Step 5 · Map scopes and roles to authorities

Right now any valid token can read notes, even one with no scopes at all. Spring Security makes decisions with authorities: plain strings on the authenticated user. By default, the resource server turns each entry in the token's scope claim into an authority with the prefix SCOPE_, so "scope": "notes:read notes:write" becomes SCOPE_notes:read and SCOPE_notes:write.

Many identity providers also put a list of roles in a separate claim. Spring knows nothing about it until you tell it. Replace SecurityConfig.java with a version that keeps the default scope mapping, adds a ROLE_ authority for each entry in a roles claim, and requires the notes:read scope to read notes:

Bash
cat > src/main/java/dev/example/notes/SecurityConfig.java <<'JAVA'
package dev.example.notes;

import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Value;
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.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
class SecurityConfig {

    @Bean
    SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/status").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/notes", "/api/notes/**").hasAuthority("SCOPE_notes:read")
                .anyRequest().authenticated())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
        return http.build();
    }

    @Bean
    JwtDecoder jwtDecoder(
            @Value("${notes.jwt.public-key-location}") RSAPublicKey publicKey,
            @Value("${notes.jwt.issuer}") String issuer,
            @Value("${notes.jwt.audience}") String audience) {
        NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey)
            .signatureAlgorithm(SignatureAlgorithm.RS256)
            .build();
        OAuth2TokenValidator<Jwt> audienceCheck = new JwtClaimValidator<List<String>>(
            JwtClaimNames.AUD, aud -> aud != null && aud.contains(audience));
        decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
            JwtValidators.createDefaultWithIssuer(issuer), audienceCheck));
        return decoder;
    }

    @Bean
    JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(SecurityConfig::authorities);
        return converter;
    }

    // "scope": "notes:read notes:write" -> SCOPE_notes:read, SCOPE_notes:write
    // "roles": ["admin"]                -> ROLE_ADMIN
    static Collection<GrantedAuthority> authorities(Jwt jwt) {
        JwtGrantedAuthoritiesConverter scopes = new JwtGrantedAuthoritiesConverter();
        List<GrantedAuthority> authorities = new ArrayList<>(scopes.convert(jwt));
        List<String> roles = jwt.getClaimAsStringList("roles");
        if (roles != null) {
            roles.forEach(role -> authorities.add(
                new SimpleGrantedAuthority("ROLE_" + role.toUpperCase(Locale.ROOT))));
        }
        return authorities;
    }
}
JAVA

The resource server finds the JwtAuthenticationConverter bean and uses it for every token. The mapping lives in a static method so your tests can reuse exactly the same rules later.

To see what Spring makes of a token, add an endpoint that reports it:

Bash
cat > src/main/java/dev/example/notes/MeController.java <<'JAVA'
package dev.example.notes;

import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class MeController {

    record Me(String subject, List<String> authorities) {}

    @GetMapping("/api/me")
    Me me(JwtAuthenticationToken authentication) {
        List<String> authorities = authentication.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .sorted()
            .toList();
        return new Me(authentication.getName(), authorities);
    }
}
JAVA

Restart the API in the second terminal, then mint one token with two scopes and the admin role, and one with no scopes. You reuse both in the next two steps, so mint them with ttl=3600 (one hour) instead of the default ten minutes; otherwise they can expire while you edit and restart, and you get 401 ... Jwt expired instead of the results shown. Run these, and every later command, in the same first terminal, because ADMIN and NOSCOPE are shell variables that exist only there:

Bash
ADMIN=$(java tools/Token.java mint scope="notes:read notes:write" roles=admin ttl=3600)
curl -s -H "Authorization: Bearer $ADMIN" http://localhost:8080/api/me; echo
NOSCOPE=$(java tools/Token.java mint ttl=3600)
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $NOSCOPE" http://localhost:8080/api/notes

Check it worked

/api/me answers {"subject":"ada","authorities":["FACTOR_BEARER","ROLE_ADMIN","SCOPE_notes:read","SCOPE_notes:write"]}. FACTOR_BEARER is added by Spring Security 7 itself and records that the caller authenticated with a bearer token. The token with no scopes now gets 403 on /api/notes: it proves who the caller is, but not that they may read notes. That is the difference between 401 (who are you?) and 403 (you may not).

Step 6 · Guard methods with @PreAuthorize

URL rules are good for broad strokes. For rules that belong to one operation, put them on the method. Turn method security on in a configuration class of its own:

Bash
cat > src/main/java/dev/example/notes/MethodSecurityConfig.java <<'JAVA'
package dev.example.notes;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@Configuration
@EnableMethodSecurity
class MethodSecurityConfig {
}
JAVA

Then replace the controller. Creating a note needs the notes:write scope, deleting one needs the admin role, and a new note's author now comes from the token's sub claim, not from anything the caller can type:

Bash
cat > src/main/java/dev/example/notes/NotesController.java <<'JAVA'
package dev.example.notes;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
class NotesController {

    record Note(long id, String text, String author) {}
    record NewNote(String text) {}

    private final Map<Long, Note> notes = new ConcurrentSkipListMap<>();
    private final AtomicLong ids = new AtomicLong();

    NotesController() {
        save("Review who can delete notes", "system");
    }

    @GetMapping("/status")
    Map<String, String> status() {
        return Map.of("status", "ok");
    }

    @GetMapping("/notes")
    Collection<Note> list() {
        return notes.values();
    }

    @PostMapping("/notes")
    @ResponseStatus(HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('SCOPE_notes:write')")
    Note create(@RequestBody NewNote body, @AuthenticationPrincipal Jwt jwt) {
        return save(body.text(), jwt.getSubject());
    }

    @DeleteMapping("/notes/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    ResponseEntity<Void> delete(@PathVariable long id) {
        return notes.remove(id) == null
            ? ResponseEntity.notFound().build()
            : ResponseEntity.noContent().build();
    }

    private Note save(String text, String author) {
        Note note = new Note(ids.incrementAndGet(), text, author);
        notes.put(note.id(), note);
        return note;
    }
}
JAVA

hasRole('ADMIN') looks for the authority ROLE_ADMIN, which your converter makes from "roles": ["admin"]. @PreAuthorize runs before the method body, so a refused caller never reaches your code.

Restart the API, then try writing with a read-only token, writing with the admin token from the last step, and deleting with each:

Bash
READER=$(java tools/Token.java mint scope="notes:read" sub=grace)
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $READER" --json '{"text":"Book the hall"}' http://localhost:8080/api/notes
curl -s -H "Authorization: Bearer $ADMIN" --json '{"text":"Book the hall"}' http://localhost:8080/api/notes; echo
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE -H "Authorization: Bearer $READER" http://localhost:8080/api/notes/1
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE -H "Authorization: Bearer $ADMIN" http://localhost:8080/api/notes/1

Check it worked

The four lines are 403, {"id":2,"text":"Book the hall","author":"ada"}, 403 and 204. The author is ada because that is the admin token's sub. You did not have to switch off CSRF protection for the POST and DELETE requests: the resource server skips the CSRF check for requests that carry a bearer token, because a browser never attaches one by itself.

Step 7 · Send bad tokens and read why they fail

A secure API rejects bad tokens, and a well-behaved one says why in the WWW-Authenticate header, using the error codes from RFC 6750. Define a helper that prints the status and that header for any token:

Bash
try_token() {
  curl -s -o /dev/null -w '%{http_code} %header{www-authenticate}\n' \
    -H "Authorization: Bearer $1" http://localhost:8080/api/notes
}
b64url() { base64 | tr -d '\n=' | tr '+/' '-_'; }

Now make six bad tokens. The first four are properly signed but wrong in one way each. The fifth is signed with a different key. The sixth takes a real token and changes the claims to sub: mallory with every permission, keeping the original signature:

Bash
EXPIRED=$(java tools/Token.java mint scope="notes:read" age=900)
WRONG_AUD=$(java tools/Token.java mint scope="notes:read" aud=billing-api)
WRONG_ISS=$(java tools/Token.java mint scope="notes:read" iss=https://evil.example)
java tools/Token.java keygen otherkeys
OTHER_KEY=$(java tools/Token.java mint scope="notes:read" key=otherkeys/private.pem)
NO_ALG="$(printf '{"alg":"none"}' | b64url).$(printf '{"iss":"https://auth.example.test","sub":"mallory","aud":"notes-api","scope":"notes:read","exp":%s}' "$(( $(date +%s) + 600 ))" | b64url)."
FORGED="${ADMIN%%.*}.$(printf '{"iss":"https://auth.example.test","sub":"mallory","aud":"notes-api","scope":"notes:read notes:write","roles":["admin"],"exp":%s}' "$(( $(date +%s) + 600 ))" | b64url).${ADMIN##*.}"
for t in "$EXPIRED" "$WRONG_AUD" "$WRONG_ISS" "$OTHER_KEY" "$NO_ALG" "$FORGED" "$NOSCOPE"; do try_token "$t"; done

The last line in the loop reuses the valid token with no scopes from earlier, as a contrast. If more than an hour has passed since you minted it, mint it again first with NOSCOPE=$(java tools/Token.java mint ttl=3600). Keep real tokens short-lived; the hour here only gives you time to work through the steps.

Check it worked

The first six lines start with 401 Bearer error="invalid_token", and each error_description names its own fault:

  • expired: Jwt expired at 2026-... (the token's exp is five minutes in the past, more than the 60-second allowance)
  • wrong audience: The aud claim is not valid
  • wrong issuer: The iss claim is not valid
  • other key: Signed JWT rejected: Invalid signature
  • alg set to none: Unsupported algorithm of none
  • forged claims: Signed JWT rejected: Invalid signature

The last line is different: 403 Bearer error="insufficient_scope". That token is genuine, so the API says "you may not", not "I do not believe you". If a client gets 401 for a token you expected to work, the description tells you which check to look at, without exposing anything an attacker could use.

These checks use the API server's clock only. A phone with the wrong time cannot break them, but an identity provider and API whose clocks drift apart can, so keep both on NTP. On patchy mobile networks, let clients refresh short-lived tokens instead of stretching token lifetimes to hours to avoid failures.

Step 8 · Test the rules with spring-security-test

Curl proves the rules today; tests keep them true when someone edits the configuration next month. spring-security-test adds a jwt() request post-processor for MockMvc. It puts a ready-made authenticated token on the request, so most tests skip the decoder and check only your authorisation rules. Two tests send no token or a malformed one, which do go through the real decoder.

Bash
cat > src/test/java/dev/example/notes/NotesSecurityTests.java <<'JAVA'
package dev.example.notes;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
class NotesSecurityTests {

    @Autowired MockMvc mvc;

    @Test
    void statusIsPublic() throws Exception {
        mvc.perform(get("/api/status")).andExpect(status().isOk());
    }

    @Test
    void notesNeedAToken() throws Exception {
        mvc.perform(get("/api/notes"))
            .andExpect(status().isUnauthorized())
            .andExpect(header().string("WWW-Authenticate", startsWith("Bearer")));
    }

    @Test
    void aGarbageTokenIsRejectedAsInvalid() throws Exception {
        mvc.perform(get("/api/notes").header("Authorization", "Bearer not-a-jwt"))
            .andExpect(status().isUnauthorized())
            .andExpect(header().string("WWW-Authenticate", containsString("invalid_token")));
    }

    @Test
    void readScopeCanList() throws Exception {
        mvc.perform(get("/api/notes").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_notes:read"))))
            .andExpect(status().isOk());
    }

    @Test
    void readScopeCannotWrite() throws Exception {
        mvc.perform(post("/api/notes")
                .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_notes:read")))
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"text\":\"hello\"}"))
            .andExpect(status().isForbidden())
            .andExpect(header().string("WWW-Authenticate", containsString("insufficient_scope")));
    }

    @Test
    void writeScopeCreatesANoteAsTheSubject() throws Exception {
        mvc.perform(post("/api/notes")
                .with(jwt().jwt(token -> token.subject("grace"))
                    .authorities(new SimpleGrantedAuthority("SCOPE_notes:write")))
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"text\":\"hello\"}"))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.author").value("grace"));
    }

    @Test
    void adminRoleClaimCanDelete() throws Exception {
        mvc.perform(delete("/api/notes/1")
                .with(jwt().jwt(token -> token.claim("roles", List.of("admin"))).authorities(SecurityConfig::authorities)))
            .andExpect(status().isNoContent());
    }

    @Test
    void writeScopeAloneCannotDelete() throws Exception {
        mvc.perform(delete("/api/notes/1")
                .with(jwt().jwt(token -> token.claim("scope", "notes:write")).authorities(SecurityConfig::authorities)))
            .andExpect(status().isForbidden());
    }
}
JAVA
./mvnw test

The last two tests pass SecurityConfig::authorities to jwt(), so the claims go through your real mapping. A typo in the role prefix would fail them. The test context loads your JwtDecoder too, which reads keys/public.pem, so run the tests from the project folder.

Check it worked

Maven ends with Tests run: 9, Failures: 0, Errors: 0, Skipped: 0 and BUILD SUCCESS: your eight tests plus the context test start.spring.io generated. Change hasRole('ADMIN') to hasRole('EDITOR') in NotesController, run ./mvnw test again, and adminRoleClaimCanDelete fails with Status expected:<204> but was:<403>. Change it back before you go on.

Step 9 · Clean up

Stop the API with Ctrl+C in the second terminal. Then remove the demo folder, which holds the project and both key pairs:

Bash
cd ~
rm -rf ~/spring-security-demo

The Maven wrapper and the libraries it downloaded stay in ~/.m2, a cache other Java projects share. Leave it if you build other Maven projects. If this was your only one, rm -rf ~/.m2 frees a few hundred megabytes.

Check it worked

ls ~/spring-security-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.