Spring Security in Spring Boot: how a request is let in or turned away

Adding spring-boot-starter-security locks every endpoint at once, and from then on each request passes through a chain of servlet filters that decide who the caller is and what they may do. This page explains that chain, then runs a Spring Boot 4.1 application through the default setup, URL rules, users and passwords, and the ordering mistakes that open or close the wrong endpoints.

Contents

How Spring Security sits in front of your application

Spring Security is a set of servlet filters. Every HTTP request passes through them before it reaches a controller, and any filter can answer the request itself: with a 401, a redirect to a login page, or a 403. Your controllers run only for requests the chain lets through, so they need no security code of their own.

Several objects work together:

  • DelegatingFilterProxy: an ordinary servlet filter that Spring Boot registers with the web server. It hands every request to a Spring bean named springSecurityFilterChain.
  • FilterChainProxy: that bean. It holds one or more SecurityFilterChain objects and runs the first one whose request matcher fits the request.
  • SecurityFilterChain: an ordered list of filters, built from the HttpSecurity configuration you write. One filter reads a Basic header, another a login form, another a session.
  • Authentication: the result of a successful login, holding the principal (who the caller is) and their authorities (what they may do, such as ROLE_ADMIN).
  • SecurityContextHolder: stores the Authentication for the current request in a ThreadLocal, so any code on that thread can ask who is calling.
  • AuthorizationFilter: the last filter in the chain. It compares the request with your rules and either lets it through or rejects it.

Two different failures come out of this chain, and they mean different things:

The two kinds of rejection
StatusMeaningTypical causeWhat the client should do
401 UnauthorizedNot authenticated: the server does not know who you areNo credentials, or wrong onesLog in, or send valid credentials
403 ForbiddenAuthenticated, but not allowedThe user lacks the role or authority the rule requiresNothing; trying again as the same user will not help

The examples on this page are complete Spring Boot 4.1 applications using Spring Security 7.1. Each starts Tomcat on a random port, calls itself with java.net.http.HttpClient, prints what happened, and stops. Spring Security 7 removed several older APIs that many tutorials still show: WebSecurityConfigurerAdapter (gone since 6.0), authorizeRequests(), .and() chaining and AntPathRequestMatcher. Configuration is now a SecurityFilterChain bean written with lambdas, as below.

What the starter does on its own

Adding spring-boot-starter-security changes behaviour before you write any configuration. The program below has a single controller and no security code at all, and it calls the endpoint four ways to show each default:

Java
package demo.security.defaultsecurity;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class DefaultSecurity {

    @RestController
    static class HelloController {
        @GetMapping("/hello")
        String hello() {
            return "hello";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(HelloController.class)
    static class App {
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static void get(String base, String label, String accept, String user) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/hello"))
                .header("Accept", accept);
        if (user != null) {
            request.header("Authorization", "Basic "
                    + Base64.getEncoder().encodeToString(user.getBytes()));
        }
        HttpResponse<String> response = HTTP.send(request.build(),
                HttpResponse.BodyHandlers.ofString());
        System.out.println(label);
        System.out.println("  status " + response.statusCode());
        response.headers().firstValue("WWW-Authenticate")
                .ifPresent(h -> System.out.println("  WWW-Authenticate: " + h));
        response.headers().firstValue("Location")
                .ifPresent(h -> System.out.println("  Location: "
                        + h.substring(h.indexOf("/", "http://".length()))));
        if (!response.body().isEmpty()) {
            System.out.println("  body: " + response.body());
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.security.user.password", "s3cret"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:" + context.getEnvironment()
                    .getProperty("local.server.port");
            get(base, "GET /hello from a script, no credentials:", "*/*", null);
            get(base, "GET /hello from a browser, no credentials:", "text/html", null);
            get(base, "GET /hello with user:wrong:", "*/*", "user:wrong");
            get(base, "GET /hello with user:s3cret:", "*/*", "user:s3cret");
        }
    }
}
Output
GET /hello from a script, no credentials:
  status 401
  WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
GET /hello from a browser, no credentials:
  status 302
  Location: /login
GET /hello with user:wrong:
  status 401
  WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
GET /hello with user:s3cret:
  status 200
  body: hello
  • A request with no credentials and Accept: */*, as a script sends, got 401 with WWW-Authenticate: Basic realm="Realm", which invites HTTP Basic login.
  • The same request with Accept: text/html, as a browser sends, got a 302 redirect to /login, the login form that Spring Security generates. The default chain decides between the two by the Accept header.
  • Wrong credentials got another 401, and user:s3cret got 200 and the body hello.

The user is called user. Without spring.security.user.password, Spring Boot generates a random password at each start and logs it with the warning "Using generated security password", which is how most people first meet Spring Security. The default chain also turns on CSRF protection, security headers such as X-Content-Type-Options and X-Frame-Options, session-based login and a logout page. As soon as you declare your own SecurityFilterChain bean, Spring Boot's default chain is no longer created, and only what you configure applies.

URL rules with authorizeHttpRequests

Real applications mix public pages, pages for any signed-in user and pages for administrators. This program has one endpoint of each kind and calls each one as an anonymous client, as a plain user and as an admin, so the nine results form a table:

Java
package demo.security.urlrules;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class UrlRules {

    @RestController
    static class Endpoints {
        @GetMapping("/public/info")
        String info() {
            return "open to everyone";
        }

        @GetMapping("/api/orders")
        String orders() {
            return "orders for any signed-in user";
        }

        @GetMapping("/admin/stats")
        String stats() {
            return "stats for admins";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Endpoints.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/public/**").permitAll()
                            .requestMatchers("/admin/**").hasRole("ADMIN")
                            .anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults());
            return http.build();
        }

        @Bean
        PasswordEncoder passwordEncoder() {
            return PasswordEncoderFactories.createDelegatingPasswordEncoder();
        }

        @Bean
        UserDetailsService users(PasswordEncoder encoder) {
            return new InMemoryUserDetailsManager(
                    User.withUsername("ann").password(encoder.encode("ann-pw"))
                            .roles("USER").build(),
                    User.withUsername("root").password(encoder.encode("root-pw"))
                            .roles("USER", "ADMIN").build());
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static String call(String base, String path, String user) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (user != null) {
            request.header("Authorization", "Basic "
                    + Base64.getEncoder().encodeToString(user.getBytes()));
        }
        HttpResponse<String> r = HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
        return r.statusCode() + (r.statusCode() == 200 ? " " + r.body() : "");
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            String[] users = {null, "ann:ann-pw", "root:root-pw"};
            for (String path : new String[] {"/public/info", "/api/orders", "/admin/stats"}) {
                System.out.println(path);
                for (String user : users) {
                    String who = user == null ? "anonymous" : user.substring(0, user.indexOf(':'));
                    System.out.printf("  %-9s -> %s%n", who, call(base, path, user));
                }
            }
        }
    }
}
Output
/public/info
  anonymous -> 200 open to everyone
  ann       -> 200 open to everyone
  root      -> 200 open to everyone
/api/orders
  anonymous -> 401
  ann       -> 200 orders for any signed-in user
  root      -> 200 orders for any signed-in user
/admin/stats
  anonymous -> 401
  ann       -> 403
  root      -> 200 stats for admins
  • /public/info answered 200 for all three callers, because permitAll() lets anyone through, signed in or not.
  • /api/orders gave 401 to the anonymous caller and 200 to both users. anyRequest().authenticated() needs a login, not a particular role.
  • /admin/stats shows both failures side by side: 401 for the anonymous caller, who is unknown, and 403 for ann, who is known but has only ROLE_USER. Only root, with ROLE_ADMIN, got 200.

hasRole("ADMIN") checks for the authority ROLE_ADMIN: the ROLE_ prefix is added for you, and User.roles("ADMIN") adds it on the user side. hasAuthority("ROLE_ADMIN") is the same check without the prefix, and is what you use for authorities that are not roles, such as orders:write. The other common rules are hasAnyRole(...), denyAll(), and access(...) with a custom AuthorizationManager.

A path pattern can also be limited to an HTTP method, for example requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN"). In Spring Security 7, string patterns are parsed as Spring's PathPattern, the same syntax as @GetMapping, so /** is allowed only at the end of a pattern.

Inside the filter chain

An application can have several chains, for example a stateless one for an API and a session-based one with a login form for a website. Printing the filters of each shows what every configuration line adds:

Java
package demo.security.filterlist;

import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.http.SessionCreationPolicy;

public class FilterList {

    @Configuration
    @EnableAutoConfiguration
    static class App {
        @Bean
        @Order(1)
        SecurityFilterChain api(HttpSecurity http) throws Exception {
            http.securityMatcher("/api/**")
                    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .csrf(csrf -> csrf.disable())
                    .sessionManagement(s -> s.sessionCreationPolicy(
                            SessionCreationPolicy.STATELESS));
            return http.build();
        }

        @Bean
        @Order(2)
        SecurityFilterChain web(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .formLogin(Customizer.withDefaults());
            return http.build();
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            FilterChainProxy proxy = context.getBean(FilterChainProxy.class);
            int n = 1;
            for (SecurityFilterChain chain : proxy.getFilterChains()) {
                System.out.println("Chain " + n++ + " (" + chain.getFilters().size()
                        + " filters):");
                chain.getFilters().forEach(f ->
                        System.out.println("  " + f.getClass().getSimpleName()));
            }
        }
    }
}
Output
Chain 1 (12 filters):
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextHolderFilter
  HeaderWriterFilter
  LogoutFilter
  BasicAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  AuthorizationFilter
Chain 2 (15 filters):
  DisableEncodeUrlFilter
  WebAsyncManagerIntegrationFilter
  SecurityContextHolderFilter
  HeaderWriterFilter
  CsrfFilter
  LogoutFilter
  UsernamePasswordAuthenticationFilter
  DefaultResourcesFilter
  DefaultLoginPageGeneratingFilter
  DefaultLogoutPageGeneratingFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  ExceptionTranslationFilter
  AuthorizationFilter
  • Chain 1 matches /api/** only, because of securityMatcher and @Order(1). It has 12 filters, including BasicAuthenticationFilter, and no CsrfFilter, because CSRF protection was disabled for it.
  • Chain 2 catches every other request. It has 15 filters: CsrfFilter, UsernamePasswordAuthenticationFilter for the login form, and three filters that generate the default login and logout pages and their stylesheet.
  • Both chains start with SecurityContextHolderFilter, which loads the login state for the request, and end with ExceptionTranslationFilter and AuthorizationFilter. When AuthorizationFilter denies a request, ExceptionTranslationFilter turns the exception into the 401, the redirect or the 403.

FilterChainProxy uses the first chain whose matcher fits and never tries the others, so the more specific chain needs the lower @Order. A chain without securityMatcher matches everything and must come last. To see this list for your own application at startup, set logging.level.org.springframework.security=DEBUG; the log then also shows which chain and which filters handle each request.

Users and password encoding

The previous programs stored users in an InMemoryUserDetailsManager; a real application loads them from a database through its own UserDetailsService, as the custom authentication page shows. Wherever users live, passwords must be stored as one-way hashes. This program shows what Spring Security's default encoder produces, the trap of an unprefixed password, and the cost of a BCrypt hash:

Java
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

public class Passwords {

    public static void main(String[] args) {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        String first = encoder.encode("correct-horse");
        String second = encoder.encode("correct-horse");
        System.out.println("Two encodings of the same password:");
        System.out.println("  " + first.substring(0, 15) + "... (" + first.length() + " chars)");
        System.out.println("  " + second.substring(0, 15) + "... (" + second.length() + " chars)");
        System.out.println("  equal strings: " + first.equals(second));
        System.out.println("  matches(correct-horse): " + encoder.matches("correct-horse", first));
        System.out.println("  matches(wrong): " + encoder.matches("wrong", first));

        System.out.println("Stored values with other ids still match:");
        String legacy = "{noop}plain-old";
        System.out.println("  " + legacy + " -> " + encoder.matches("plain-old", legacy));
        System.out.println("  upgradeEncoding needed: " + encoder.upgradeEncoding(legacy));

        System.out.println("A stored value with no {id} prefix:");
        try {
            encoder.matches("plain-old", "plain-old");
        } catch (IllegalArgumentException e) {
            System.out.println("  " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }

        System.out.println("Cost of one encode, BCrypt strength 10 vs 12 (rough):");
        for (int strength : new int[] {10, 12}) {
            BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(strength);
            bcrypt.encode("warm-up");                       // let the JIT compile BCrypt first
            long best = Long.MAX_VALUE;
            for (int run = 0; run < 3; run++) {
                long start = System.nanoTime();
                bcrypt.encode("correct-horse");
                best = Math.min(best, System.nanoTime() - start);
            }
            System.out.println("  strength " + strength + ": " + best / 1000000 + " ms");
        }
    }
}
Output
Two encodings of the same password:
  {bcrypt}$2a$10$... (68 chars)
  {bcrypt}$2a$10$... (68 chars)
  equal strings: false
  matches(correct-horse): true
  matches(wrong): false
Stored values with other ids still match:
  {noop}plain-old -> true
  upgradeEncoding needed: true
A stored value with no {id} prefix:
  IllegalArgumentException: Given that there is no default password encoder configured, each password must have a password encoding prefix. Please either prefix this password with '{noop}' or set a default password encoder in `DelegatingPasswordEncoder`.
Cost of one encode, BCrypt strength 10 vs 12 (rough):
  strength 10: 62 ms
  strength 12: 280 ms
  • Encoding correct-horse twice gave two different 68-character strings, because BCrypt adds a random salt each time. matches still recognised the password, because the salt is stored inside the hash.
  • Each value starts with {bcrypt}, then $2a$10$: BCrypt version 2a with strength 10. The prefix in braces tells DelegatingPasswordEncoder which encoder to use to check it.
  • {noop}plain-old matched too: {noop} marks a plain-text password, and upgradeEncoding returned true, a signal that the value should be re-hashed with the current default the next time the user logs in.
  • A stored value with no prefix at all threw IllegalArgumentException. This is the error people meet when they move old plain-text or bare BCrypt hashes into a new Spring Security application; add the prefix to the stored values, or set a default encoder for unprefixed ones with setDefaultPasswordEncoderForMatches.
  • Strength 12 took about 4 to 5 times as long as strength 10, as expected: each step of strength doubles the work (rough comparison, best of 3 runs on a 2-core Intel Xeon at 2.10 GHz).

The slowness is the point: it makes guessing passwords from a stolen table expensive. It also means every login costs real CPU time, so choose a strength that takes a fraction of a second on your servers, and never hash passwords on each request; HTTP Basic does exactly that, which is one reason APIs move to tokens after login, as the JWT access and refresh token page shows.

Reading the current user

Once a request is authenticated, code often needs to know who made it. Spring offers several ways in, and this controller uses all of them in one request, including two background threads that show where the information stops:

Java
package demo.security.currentuser;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.Principal;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.concurrent.DelegatingSecurityContextExecutorService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class CurrentUser {

    static String whoIsCalling() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth == null ? "nobody" : auth.getName();
    }

    @RestController
    static class MeController implements DisposableBean {
        private final ExecutorService pool = Executors.newSingleThreadExecutor();
        private final ExecutorService wrapped = new DelegatingSecurityContextExecutorService(
                Executors.newSingleThreadExecutor());

        @Override
        public void destroy() {
            pool.shutdown();
            wrapped.shutdown();
        }

        @GetMapping("/me")
        String me(Authentication authentication, Principal principal,
                  @AuthenticationPrincipal UserDetails user) {
            return "Authentication.getName() = " + authentication.getName()
                    + "\n  Principal.getName()      = " + principal.getName()
                    + "\n  UserDetails authorities  = " + user.getAuthorities()
                    + "\n  SecurityContextHolder    = " + whoIsCalling()
                    + "\n  plain pool thread        = "
                    + CompletableFuture.supplyAsync(CurrentUser::whoIsCalling, pool).join()
                    + "\n  delegating pool thread   = "
                    + CompletableFuture.supplyAsync(CurrentUser::whoIsCalling, wrapped).join();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(MeController.class)
    static class App {
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.security.user.name", "ann",
                "spring.security.user.password", "ann-pw",
                "spring.security.user.roles", "USER"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/me"))
                    .header("Authorization", "Basic "
                            + Base64.getEncoder().encodeToString("ann:ann-pw".getBytes()))
                    .build();
            HttpResponse<String> response = HttpClient.newHttpClient()
                    .send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("GET /me as ann -> " + response.statusCode());
            System.out.println("  " + response.body());
        }
    }
}
Output
GET /me as ann -> 200
  Authentication.getName() = ann
  Principal.getName()      = ann
  UserDetails authorities  = [ROLE_USER]
  SecurityContextHolder    = ann
  plain pool thread        = nobody
  delegating pool thread   = ann
  • An Authentication parameter, a java.security.Principal parameter and a call to SecurityContextHolder all gave ann. They read the same object.
  • @AuthenticationPrincipal UserDetails gave the user object itself, here with the authorities [ROLE_USER]. With a custom UserDetails class it can hand your own user type straight to the controller.
  • On a plain pool thread, the answer was nobody. The context lives in a ThreadLocal of the request thread, so code passed to another executor runs without it.
  • On a pool wrapped in DelegatingSecurityContextExecutorService, the answer was ann again: the wrapper copies the caller's context to the task's thread for the length of the task and clears it afterwards.

Use the controller parameters in web code, since they are easy to test, and SecurityContextHolder in services that are not called from a controller. The ThreadLocal page explains why the value disappears on other threads.

Rule order: the first match wins

authorizeHttpRequests checks its rules from top to bottom and stops at the first pattern that matches. Putting a broad pattern before a narrow one is the most common security configuration bug, so this program starts three applications whose rules differ only in order:

Java
package demo.security.matcherorder;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class MatcherOrder {

    @RestController
    static class Endpoints {
        @GetMapping("/api/health")
        String health() {
            return "UP";
        }

        @GetMapping("/api/orders")
        String orders() {
            return "orders";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Endpoints.class)
    static class WrongOrder {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/api/**").authenticated()
                            .requestMatchers("/api/health").permitAll()   // never reached
                            .anyRequest().denyAll())
                    .httpBasic(Customizer.withDefaults());
            return http.build();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Endpoints.class)
    static class RightOrder {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/api/health").permitAll()
                            .requestMatchers("/api/**").authenticated()
                            .anyRequest().denyAll())
                    .httpBasic(Customizer.withDefaults());
            return http.build();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Endpoints.class)
    static class AnyRequestFirst {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                    .anyRequest().authenticated()
                    .requestMatchers("/api/health").permitAll());
            return http.build();
        }
    }

    static void run(Class<?> config) throws Exception {
        System.out.println(config.getSimpleName() + ":");
        SpringApplication app = new SpringApplication(config);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "OFF", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            HttpResponse<String> r = HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(URI.create(base + "/api/health")).build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("  GET /api/health, anonymous -> " + r.statusCode());
        } catch (RuntimeException e) {
            Throwable root = e;
            while (root.getCause() != null) {
                root = root.getCause();
            }
            System.out.println("  startup failed: " + root.getClass().getSimpleName()
                    + ": " + root.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        run(WrongOrder.class);
        run(RightOrder.class);
        run(AnyRequestFirst.class);
    }
}
Output
WrongOrder:
  GET /api/health, anonymous -> 401
RightOrder:
  GET /api/health, anonymous -> 200
AnyRequestFirst:
  startup failed: IllegalStateException: Can't configure requestMatchers after anyRequest
  • In WrongOrder, /api/health got 401, although a line says permitAll(). The request matched /api/** first, which needs a login, and the later rule was never consulted.
  • In RightOrder, the specific rule comes first, and the same request got 200.
  • In AnyRequestFirst, the application did not start at all: Spring Security refuses any rule after anyRequest() with Can't configure requestMatchers after anyRequest. This trap at least fails loudly.

Write rules from the most specific to the most general, and end with anyRequest(). Ending with anyRequest().denyAll() instead of authenticated() is safer still, because an endpoint added later stays closed until someone writes a rule for it. The same first-match rule applies to the chains themselves, as the filter chain section showed.

Other things that commonly go wrong

  • Disabling CSRF without thinking: an API that only accepts tokens in a header does not need CSRF protection, but an application that logs users in with a session cookie does. The CSRF and CORS page explains when it is safe to turn off.
  • Securing only URLs: URL rules protect controllers, but not services that are also called from scheduled jobs or message listeners. Method security puts the check on the service itself.
  • Error pages behind the chain: when a controller throws, Spring Boot forwards the request to /error, and that forward is checked against the rules too. With the rules from the URL rules section, an anonymous call to a permitAll() endpoint that throws returns 401 with an empty body instead of a 500, which hides the real error. Add requestMatchers("/error").permitAll() to the chain.
  • Tests that start the whole server: spring-security-test adds @WithMockUser and MockMvc helpers such as httpBasic(...) and csrf(), so most rules can be tested without real users or a running server.

Choosing an authentication setup

Common setups and what to configure
ApplicationConfiguration
Server-rendered websiteformLogin(), sessions, CSRF on
Internal tool or quick prototypehttpBasic() over HTTPS, users from spring.security.user.* or a small UserDetailsService
API that issues its own tokensLogin endpoint plus JWT access and refresh tokens, stateless sessions: see JWT refresh tokens
API behind an identity provider (Keycloak, Okta, Entra ID)oauth2ResourceServer().jwt(): see OAuth2 resource server
Website with "log in with Google"oauth2Login()
Users in your own databaseA custom UserDetailsService: see custom authentication
Rules about individual records, such as "only the owner may edit"Method security, or ACLs for permissions stored per object
WebFlux applicationSecurityWebFilterChain with ServerHttpSecurity: see reactive security

Whatever you choose, keep one SecurityFilterChain per kind of client, order its rules from specific to general, and test the 401 and 403 cases as carefully as the 200 ones.