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 What the starter does on its own URL rules with authorizeHttpRequests Inside the filter chain Users and password encoding Reading the current user Rule order: the first match wins Other things that commonly go wrong Choosing an authentication setup
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
objects and runs the first one whose request matcher fits the request.SecurityFilterChain - SecurityFilterChain: an ordered list of filters, built from the
configuration you write. One filter reads a Basic header, another a login form, another a session.HttpSecurity - 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
for the current request in aAuthentication , so any code on that thread can ask who is calling.ThreadLocal - 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:
| Status | Meaning | Typical cause | What the client should do |
|---|---|---|---|
| 401 Unauthorized | Not authenticated: the server does not know who you are | No credentials, or wrong ones | Log in, or send valid credentials |
| 403 Forbidden | Authenticated, but not allowed | The user lacks the role or authority the rule requires | Nothing; 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.HttpClientWebSecurityConfigurerAdapterauthorizeRequests().and()AntPathRequestMatcherSecurityFilterChain
What the starter does on its own
Adding spring-boot-starter-security
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");
}
}
}
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
, as a script sends, got 401 withAccept: */* , which invites HTTP Basic login.WWW-Authenticate: Basic realm="Realm" - The same request with
, as a browser sends, got a 302 redirect toAccept: text/html , the login form that Spring Security generates. The default chain decides between the two by the/login header.Accept - Wrong credentials got another 401, and
got 200 and the bodyuser:s3cret .hello
The user is called userspring.security.user.passwordX-Content-Type-OptionsX-Frame-OptionsSecurityFilterChain
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:
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));
}
}
}
}
}
/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
answered 200 for all three callers, because/public/info lets anyone through, signed in or not.permitAll() gave 401 to the anonymous caller and 200 to both users./api/orders needs a login, not a particular role.anyRequest().authenticated() shows both failures side by side: 401 for the anonymous caller, who is unknown, and 403 for/admin/stats , who is known but has onlyann . OnlyROLE_USER , withroot , got 200.ROLE_ADMIN
hasRole("ADMIN")ROLE_ADMINROLE_User.roles("ADMIN")hasAuthority("ROLE_ADMIN")orders:writehasAnyRole(...)denyAll()access(...)AuthorizationManager
A path pattern can also be limited to an HTTP method, for example requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")PathPattern@GetMapping/**
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:
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()));
}
}
}
}
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
only, because of/api/** andsecurityMatcher . It has 12 filters, including@Order(1) , and noBasicAuthenticationFilter , because CSRF protection was disabled for it.CsrfFilter - Chain 2 catches every other request. It has 15 filters:
,CsrfFilter for the login form, and three filters that generate the default login and logout pages and their stylesheet.UsernamePasswordAuthenticationFilter - Both chains start with
, which loads the login state for the request, and end withSecurityContextHolderFilter andExceptionTranslationFilter . WhenAuthorizationFilter denies a request,AuthorizationFilter turns the exception into the 401, the redirect or the 403.ExceptionTranslationFilter
FilterChainProxy@OrdersecurityMatcherlogging.level.org.springframework.security=DEBUG
Users and password encoding
The previous programs stored users in an InMemoryUserDetailsManagerUserDetailsService
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");
}
}
}
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
twice gave two different 68-character strings, because BCrypt adds a random salt each time.correct-horse still recognised the password, because the salt is stored inside the hash.matches - Each value starts with
, then{bcrypt} : BCrypt version 2a with strength 10. The prefix in braces tells$2a$10$ which encoder to use to check it.DelegatingPasswordEncoder matched too:{noop}plain-old marks a plain-text password, and{noop} returnedupgradeEncoding , a signal that the value should be re-hashed with the current default the next time the user logs in.true- A stored value with no prefix at all threw
. 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 withIllegalArgumentException .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
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:
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());
}
}
}
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
parameter, aAuthentication parameter and a call tojava.security.Principal all gaveSecurityContextHolder . They read the same object.ann gave the user object itself, here with the authorities@AuthenticationPrincipal UserDetails . With a custom[ROLE_USER] class it can hand your own user type straight to the controller.UserDetails- On a plain pool thread, the answer was
. The context lives in anobody of the request thread, so code passed to another executor runs without it.ThreadLocal - On a pool wrapped in
, the answer wasDelegatingSecurityContextExecutorService again: the wrapper copies the caller's context to the task's thread for the length of the task and clears it afterwards.ann
Use the controller parameters in web code, since they are easy to test, and SecurityContextHolder
Rule order: the first match wins
authorizeHttpRequests
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);
}
}
WrongOrder:
GET /api/health, anonymous -> 401
RightOrder:
GET /api/health, anonymous -> 200
AnyRequestFirst:
startup failed: IllegalStateException: Can't configure requestMatchers after anyRequest
- In
,WrongOrder got 401, although a line says/api/health . The request matchedpermitAll() first, which needs a login, and the later rule was never consulted./api/** - In
, the specific rule comes first, and the same request got 200.RightOrder - In
, the application did not start at all: Spring Security refuses any rule afterAnyRequestFirst withanyRequest() . This trap at least fails loudly.Can't configure requestMatchers after anyRequest
Write rules from the most specific to the most general, and end with anyRequest()anyRequest().denyAll()authenticated()
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
, and that forward is checked against the rules too. With the rules from the URL rules section, an anonymous call to a/error endpoint that throws returns 401 with an empty body instead of a 500, which hides the real error. AddpermitAll() to the chain.requestMatchers("/error").permitAll() - Tests that start the whole server:
addsspring-security-test and MockMvc helpers such as@WithMockUser andhttpBasic(...) , so most rules can be tested without real users or a running server.csrf()
Choosing an authentication setup
| Application | Configuration |
|---|---|
| Server-rendered website | formLogin() |
| Internal tool or quick prototype | httpBasic()spring.security.user.*UserDetailsService |
| API that issues its own tokens | Login endpoint plus JWT access and refresh tokens, stateless sessions: see |
| API behind an identity provider (Keycloak, Okta, Entra ID) | oauth2ResourceServer().jwt() |
| Website with "log in with Google" | oauth2Login() |
| Users in your own database | A custom UserDetailsService |
| Rules about individual records, such as "only the owner may edit" | |
| WebFlux application | SecurityWebFilterChainServerHttpSecurity |
Whatever you choose, keep one SecurityFilterChain