The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
One SecurityConfig class replaces Boot's default lock: twelve filters, a rule that only ADMIN may delete tickets, two in-memory users, and four curl calls that answer 401, 200, 403 and 204. Plus the rule order that stops the app from starting.
What you will learn
- Replace Boot's default chain with your own SecurityFilterChain bean
- Read the filter list Spring prints at startup
- Write URL rules with requestMatchers and hasRole, and tell 401 from 403
- Put the specific rule first and anyRequest last
Before you start
- Spring Boot Security Defaults
- A Spring Boot REST API
With the security starter, Relay's API has a lock on it. But that lock is the same for everybody: one generated user, and every URL just needs a login. Real rules sound more like this: any agent may read tickets, only an admin may delete one. That's what your own security filter chain is for.
Where the chain sits
Every request meets the security filter chain before any controller. The chain decides who you are (authentication) and whether you may do this (authorization). If either answer is no, the request stops there, and your controller never runs.
SecurityConfig: our chain and our users
Security is on the list of things a person writes by hand in this course, so type this one yourself:
package org.studyeasy.relay.security;
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.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // no form, no cookie
.sessionManagement(s -> s
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.DELETE, "/api/tickets/**")
.hasRole("ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults()); // name + password each time
return http.build();
}
@Bean
UserDetailsService users() { // two people, in memory
return new InMemoryUserDetailsManager(
User.withUsername("liam").password("{noop}<password>")
.roles("AGENT").build(),
User.withUsername("sophia").password("{noop}<password>")
.roles("ADMIN").build());
}
}
The first bean is the whole chain, built by one method:
- CSRF off, sessions stateless. Every request carries its own login, so there's no session cookie to protect.
- The rules, top to bottom. A
DELETEon/api/tickets/**needs theADMINrole. Anything else just needs a login. httpBasic: the name and password travel with every request.
The second bean gives Spring a UserDetailsService, so Boot makes no user of its own and the "generated security password" line disappears from the log. Liam is an agent, Sophia is an admin. {noop} means the password is stored exactly as typed: fine for two demo users, never for real ones (real users and BCrypt come in Users in the Database).
The filter list, printed at startup
Turn on logging.level.org.springframework.security: DEBUG and Spring prints the chain your bean built:
DEBUG o.s.s.web.DefaultSecurityFilterChain : Will secure any request with filters:
DisableEncodeUrlFilter
WebAsyncManagerIntegrationFilter
SecurityContextHolderFilter
HeaderWriterFilter
LogoutFilter
BasicAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
AuthorizationFilter
Twelve filters, in order, and you wrote none of them. Three are worth knowing by name. SecurityContextHolderFilter (3rd) opens the empty box that will hold the Authentication. BasicAuthenticationFilter (6th) reads the login from the header and checks the password. ExceptionTranslationFilter (11th) turns a refusal into a 401 or 403. And AuthorizationFilter (12th) applies your rules.
One request walks down the chain
The Run window logs exactly that path:
DEBUG o.s.security.web.FilterChainProxy : Securing DELETE /api/tickets/5
DEBUG o.s.s.a.dao.DaoAuthenticationProvider : Authenticated user
DEBUG o.s.s.w.a.www.BasicAuthenticationFilter : Set SecurityContextHolder to UsernamePasswordAuthenticationToken [... Username=liam ... ROLE_AGENT ...]
DEBUG o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code
Four calls, four answers
curl -i http://localhost:8080/api/tickets
curl -i -u liam:<password> http://localhost:8080/api/tickets
curl -i -u liam:<password> -X DELETE http://localhost:8080/api/tickets/5
curl -i -u sophia:<password> -X DELETE http://localhost:8080/api/tickets/5
| Call | Answer | Why |
|---|---|---|
| No credentials | 401 | nobody is logged in; WWW-Authenticate: Basic realm="Realm" |
| Liam reads | 200 | any login may read; the 50 tickets come back |
| Liam deletes | 403 | logged in, but the rule says ADMIN |
| Sophia deletes | 204 | ADMIN, so the controller runs |
The 403 body is {"timestamp":"2026-10-26T00:41:56.947Z","status":403,"error":"Forbidden","path":"/api/tickets/5"}. A second delete of ticket 5 as Sophia gives 404: it's already gone. And a wrong password for Liam gives 401, not 403.
Remember it like this: 401 = who are you? 403 = I know who you are, and the answer is no.
Break it: the catch-all first
Swap the rules so .anyRequest().authenticated() comes before the delete rule, and start the app:
ERROR o.s.boot.SpringApplication : Application run failed
Caused by: java.lang.IllegalStateException: Can't configure requestMatchers after anyRequest
at org.studyeasy.relay.security.SecurityConfig.lambda$api$2(SecurityConfig.java:25)
anyRequest() means "everything else", so a rule after it could never be reached. Spring refuses to build the chain at all, which is much better than a rule that silently never applies. The specific rule goes first; anyRequest goes last.
Common mistakes
hasRole("ROLE_ADMIN").hasRoleadds theROLE_prefix itself; writehasRole("ADMIN").- Hiding the delete button and calling it security. Only the server's rule stops a curl call.
- Keeping
{noop}passwords anywhere but a throwaway demo. - Broad rules first. Rules are checked top to bottom; the first match wins.
Try it yourself
Add a rule so that POST /api/tickets/*/comments needs the AGENT role. Where in the list does it go, and what does Sophia (ADMIN only) get when she calls it?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.
Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.
Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.
Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.
