Spring Framework
Spring Security Basics: Filter Chain, Authentication and Authorization
Intermediate7 min readUpdated
Spring Security is a chain of servlet filters configured through a SecurityFilterChain bean. After this guide you will understand how a request is authenticated and authorized, how to declare users and encode passwords correctly, how to protect URLs and methods with the lambda DSL and @PreAuthorize, what CSRF protection does and when to disable it, and how the same model extends to token-based APIs.
What you will learn
- Explain the roles of DelegatingFilterProxy, FilterChainProxy and the individual security filters
- Configure a SecurityFilterChain with the lambda DSL for form login, HTTP Basic and stateless APIs
- Provide users through UserDetailsService and store passwords with a DelegatingPasswordEncoder
- Authorize requests by URL pattern and methods with @PreAuthorize, and distinguish roles from authorities
- Describe what CSRF protection guards against and decide when it can be disabled
Security is the concern most applications get wrong not because it is hard to add but because it is hard to add everywhere. Spring Security solves that by inserting itself in front of every request as a servlet filter chain and in front of chosen methods as an AOP interceptor, so that authentication and authorization are declared once and enforced consistently. This guide covers Spring Security 6.x as used with Spring Framework 6 on Java 17 or later, with the Java configuration model that replaced WebSecurityConfigurerAdapter; OAuth 2.0 and token formats themselves are covered in the Security subject.
Architecture: the filter chain
The servlet container knows one filter: DelegatingFilterProxy, registered under the name springSecurityFilterChain. It exists so that a container-managed filter can delegate to a Spring bean. That bean is FilterChainProxy, which holds one or more SecurityFilterChain instances, each matched to a request pattern. For a request, the first matching chain runs its ordered list of filters — around fifteen for a typical form-login setup. The ones worth knowing:
| Filter | Responsibility |
|---|---|
SecurityContextHolderFilter | Loads the SecurityContext (from the session, by default) into SecurityContextHolder for the request and clears it afterwards |
CsrfFilter | Rejects state-changing requests that lack a valid CSRF token |
UsernamePasswordAuthenticationFilter | Handles the login form POST |
BasicAuthenticationFilter | Handles the Authorization: Basic header |
BearerTokenAuthenticationFilter | Handles Authorization: Bearer for resource servers |
ExceptionTranslationFilter | Turns AuthenticationException into a challenge (redirect to login, 401) and AccessDeniedException into 403 |
AuthorizationFilter | Applies the authorizeHttpRequests rules — the last filter before your application |
Authentication is a two-step conversation. A filter builds an unauthenticated Authentication token from the request — username and password, a bearer token — and hands it to an AuthenticationManager. The standard implementation, ProviderManager, tries each AuthenticationProvider until one supports the token; DaoAuthenticationProvider loads the user through a UserDetailsService, checks the password with a PasswordEncoder and returns a fully populated Authentication carrying the user's GrantedAuthority list. The filter stores it in the SecurityContextHolder and, for session-based apps, persists it in the HttpSession so subsequent requests skip the login.
Authorization happens later, twice: AuthorizationFilter checks the URL rules, and if method security is enabled an AOP interceptor checks @PreAuthorize on the invoked method. Both consult an AuthorizationManager with the current Authentication.
Configuring a SecurityFilterChain
Since Spring Security 5.7 the configuration is a bean, not a subclass. With Spring Boot, the presence of spring-boot-starter-security registers the filter; in a plain Spring MVC WAR you additionally declare a class extending AbstractSecurityWebApplicationInitializer so the container picks up DelegatingFilterProxy.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/about", "/css/**", "/js/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers(HttpMethod.POST, "/orders/**").hasAuthority("orders:write")
.anyRequest().authenticated())
.formLogin(form -> form
.loginPage("/login") // your own GET /login view; POST /login is handled by the filter
.permitAll())
.logout(logout -> logout.logoutSuccessUrl("/"))
.httpBasic(Customizer.withDefaults()); // also accept Basic, for scripts
return http.build();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
var alice = User.withUsername("alice")
.password(encoder.encode("correct horse battery staple"))
.roles("USER", "ADMIN") // stored as ROLE_USER, ROLE_ADMIN
.build();
var bob = User.withUsername("bob")
.password(encoder.encode("bob-password-2026"))
.authorities("ROLE_USER", "orders:write") // fine-grained: a role plus a permission
.build();
return new InMemoryUserDetailsManager(alice, bob);
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
The lambda style is the only DSL in Spring Security 7; the older chained .and() form was deprecated in 6.1, so write the lambda form now. Rules in authorizeHttpRequests are evaluated in declaration order and the first match wins, so specific patterns must precede anyRequest(). permitAll still runs the request through the chain — the user is identified if a session exists — whereas web.ignoring() skips security entirely and should be reserved for truly static assets.
hasRole("ADMIN") checks for the authority ROLE_ADMIN; hasAuthority("orders:write") checks the literal string. Roles are coarse groups, authorities are individual permissions; large systems usually store permissions and derive them from roles at login.
Users and passwords
The in-memory manager above is for demos and tests. Production applications implement UserDetailsService against their own store:
@Service
public class AccountUserDetailsService implements UserDetailsService {
private final AccountRepository accounts;
public AccountUserDetailsService(AccountRepository accounts) { this.accounts = accounts; }
@Override
public UserDetails loadUserByUsername(String username) {
Account a = accounts.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException(username)); // message is not shown to the client
return User.withUsername(a.email())
.password(a.passwordHash()) // already encoded, e.g. "{bcrypt}$2a$10$…"
.authorities(a.permissions().stream().map(SimpleGrantedAuthority::new).toList())
.accountLocked(a.locked())
.disabled(!a.active())
.build();
}
}
JdbcUserDetailsManager and an LDAP variant exist for standard schemas. Whatever the store, passwords must be hashed with a slow, salted algorithm. PasswordEncoderFactories.createDelegatingPasswordEncoder() returns a DelegatingPasswordEncoder that encodes with bcrypt by default and prefixes each hash with an identifier — {bcrypt}, {argon2}, {pbkdf2} — so that the algorithm can be upgraded later while old hashes still verify. Never store plain text; {noop} exists only for tests. Because verification is deliberately slow (bcrypt at the default strength takes tens of milliseconds or more per check), authenticate once per session rather than on every request, which is exactly what session-based security does.
Method security
URL rules protect entry points; method security protects the operations behind them, including ones reached through other paths — a scheduled job, a message listener, a second controller. @EnableMethodSecurity (which replaced @EnableGlobalMethodSecurity in 6.0) activates @PreAuthorize, @PostAuthorize, @PreFilter and @PostFilter with Spring Expression Language:
@Service
public class OrderService {
@PreAuthorize("hasAuthority('orders:write')")
public Order place(CreateOrder cmd) { … }
@PreAuthorize("hasRole('ADMIN') or #customerId == authentication.name")
public List<Order> ordersOf(String customerId) { … }
@PostAuthorize("returnObject.customerId == authentication.name or hasRole('SUPPORT')")
public Order get(long id) { … }
}
Because this is AOP, the usual proxy rules apply: the check runs only when the call arrives through the proxy, not on self-invocation, and a denied call throws AccessDeniedException — which, if it escapes to the web layer, ExceptionTranslationFilter turns into a 403. Put the annotations on the service layer, where the business operation is defined, rather than on controllers that merely forward to it.
CSRF protection
A cross-site request forgery attack tricks a logged-in user's browser into sending a state-changing request — a form POST to your site from a page the attacker controls — and the browser attaches the session cookie automatically. Spring Security defends by requiring every non-safe request (POST, PUT, PATCH, DELETE) to carry a token that the attacker's page cannot read: the CsrfFilter compares the token in the request (a form field named _csrf or the X-CSRF-TOKEN header) with the one stored server-side. Thymeleaf's Spring integration and the JSP form tag add the hidden field automatically; a JavaScript client reads it from the XSRF-TOKEN cookie when you configure CookieCsrfTokenRepository.withHttpOnlyFalse().
Spring Security 6 changed two defaults: the token is loaded lazily (only when a request actually needs it) and the value exposed to the request is masked per request by XorCsrfTokenRequestAttributeHandler, the new default handler, to resist BREACH-style attacks. Both are transparent for form-based apps and slightly more involved for single-page apps that read the token from a cookie; the reference guide's SPA section shows the exact configuration.
The protection is only relevant when the browser authenticates automatically. An API authenticated by a bearer token in a header is immune, which is why the stateless configuration below disables it.
Stateless APIs
A resource server that validates bearer tokens on every request needs no session, no login page and no CSRF:
@Bean
@Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.securityMatcher("/api/**") // this chain only for the API
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
.anyRequest().authenticated())
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) // validates JWTs against the issuer's JWKS
.exceptionHandling(e -> e.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()));
return http.build();
}
Multiple chains are ordered with @Order; the first whose securityMatcher matches handles the request, so the API chain must come before a catch-all web chain. oauth2ResourceServer().jwt() needs the spring-security-oauth2-resource-server and spring-security-oauth2-jose modules and an issuer or JWK Set URI; the token's scopes become authorities prefixed SCOPE_, which you can remap with a JwtAuthenticationConverter. Decoding a token to see its claims while debugging is a job for the JWT decoder — never for trusting it; only the resource server's signature check does that.
Accessing the current user
@GetMapping("/me")
public ProfileResponse me(@AuthenticationPrincipal UserDetails user) {
return profiles.forUsername(user.getUsername());
}
// in a service, without web types
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
boolean admin = auth.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
The context is held in a ThreadLocal for the duration of the request. Work handed to another thread — @Async, an executor, a parallel stream — does not see it unless you wrap the executor with DelegatingSecurityContextExecutor or set the holder strategy to MODE_INHERITABLETHREADLOCAL.
Common mistakes
Ordering anyRequest() first. Every later rule is unreachable; Spring Security 6 throws at startup for rules declared after anyRequest(), but a broad /** pattern placed early silently shadows the specific ones.
Prefixing hasRole with ROLE_. hasRole("ROLE_ADMIN") throws IllegalArgumentException. Use hasAuthority if you want the literal string.
Encoding passwords at login instead of at registration. PasswordEncoder.matches(raw, encoded) is what verification uses; never compare encode(raw) to the stored hash — salted algorithms produce a different output every time.
Disabling CSRF on a session-cookie application "because it was in the way". You just enabled the attack the filter prevents. Fix the form or SPA integration instead.
Revealing whether a username exists. UsernameNotFoundException is converted to a generic bad-credentials error by default (hideUserNotFoundExceptions); do not undo that, and keep the login page's message identical for wrong user and wrong password.
Relying on URL rules alone. A new controller mapping outside the protected patterns is open by default unless anyRequest().authenticated() closes the gap; method security on the service catches what the URL layer misses.
Forgetting CORS in the security chain. Preflight OPTIONS requests hit the filter chain before MVC; call http.cors(Customizer.withDefaults()) with a CorsConfigurationSource bean so they are permitted.
Key takeaways
- Spring Security is a
FilterChainProxyof ordered filters registered throughDelegatingFilterProxy; authentication filters populateSecurityContextHolder,AuthorizationFilterenforces URL rules. - Configure with
SecurityFilterChainbeans and the lambda DSL;WebSecurityConfigurerAdapteris gone in 6.0. - Users come from a
UserDetailsService; passwords are stored with aDelegatingPasswordEncoder(bcrypt by default) and verified withmatches. hasRoleadds theROLE_prefix,hasAuthoritydoes not;@PreAuthorizeon services protects operations regardless of entry point, subject to AOP proxy rules.- CSRF protection matters whenever the browser authenticates automatically; stateless bearer-token APIs disable it and set
SessionCreationPolicy.STATELESS. - The security context is thread-bound; propagate it explicitly to background work.
Sources and further reading
Frequently asked questions
- Where did WebSecurityConfigurerAdapter go?
- It was deprecated in Spring Security 5.7 and removed in 6.0. Instead of extending a base class you declare a SecurityFilterChain bean that receives an HttpSecurity builder, and a UserDetailsService bean instead of overriding configure(AuthenticationManagerBuilder). Several chains can coexist, each matched to a URL prefix with securityMatcher.
- What is the difference between hasRole and hasAuthority?
- Both compare against the GrantedAuthority strings on the Authentication. hasRole('ADMIN') automatically prefixes ROLE_, so it checks for the authority ROLE_ADMIN; hasAuthority('ROLE_ADMIN') checks the literal string. Use hasRole for coarse roles and hasAuthority for fine-grained permissions such as orders:write. Never pass a string that already starts with ROLE_ to hasRole — it throws.
- Should I disable CSRF protection for a REST API?
- Only if the API is not authenticated by anything the browser sends automatically. If clients authenticate with a bearer token in an Authorization header, a cross-site page cannot forge the request and CSRF protection adds nothing; disable it and set the session policy to STATELESS. If the API uses session cookies — a single-page app on the same site, for example — keep it enabled and use the cookie-based token repository so JavaScript can read the token.
- How do I get the current user in a controller or service?
- In a controller, declare an @AuthenticationPrincipal UserDetails parameter or a java.security.Principal. In a service, SecurityContextHolder.getContext().getAuthentication() returns the current Authentication; the context is bound to the request thread by SecurityContextHolderFilter, so it is not available on other threads unless you propagate it deliberately.