Skip to content
javahacks.dev
Security

How to Configure Spring Security With SecurityFilterChain

Configure Spring Security with a SecurityFilterChain bean: authorize requests, form login, logout, CSRF, headers, multiple chains and testing the rules.

6 min read
Summarize in AI
Flat illustration of a security filter chain guarding a request, with the Spring Security, Spring Boot, Keycloak and OWASP logos.

The SecurityFilterChain is the central piece of Spring Security configuration. It describes which filters run for a request and what each one requires, and a Spring Boot application can have several, each applying to a different set of URLs. Getting its rules right is mostly a matter of order and matchers. This guide builds a basic chain, adds users and a password encoder, separates a web chain from an API chain, shows custom filters and exception handling, tests the rules and lists the mistakes that cause most security reviews to fail. Examples use Spring Boot 4 and Spring Security 7.

A basic chain

java
@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/css/**", "/login").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/dashboard"))
            .logout(logout -> logout.logoutSuccessUrl("/"))
            .headers(h -> h.contentSecurityPolicy(csp ->
                csp.policyDirectives("default-src 'self'")));
        return http.build();
    }
}

Rules are evaluated top to bottom and the first match wins. Put specific matchers first and anyRequest() last. A missing final rule leaves unmatched requests with the default of authenticated in recent versions, but write it explicitly, so a reader does not need to know the default. The lambda style is the current API: the older chained form with and() is removed. The headers block adds a content security policy, one of several response headers that Spring Security sets by default.

Users and passwords

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

The delegating encoder stores each hash with an algorithm prefix, such as {bcrypt}, so you can move to a stronger algorithm later without invalidating existing passwords. Provide a UserDetailsService, usually backed by a database, as shown in a custom UserDetailsService. Never store plain-text or reversibly encrypted passwords, and never log them. Form login with a persistent token is covered in its own guide.

Separate chains for API and web

java
@Bean
@Order(1)
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http.securityMatcher("/api/**")
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .csrf(csrf -> csrf.disable());
    return http.build();
}

The chain with the lower @Order is consulted first, and its securityMatcher decides whether it applies to a request; the web chain above, with no matcher, catches the rest. A stateless token API does not use cookies for authentication, so CSRF protection, which defends cookie sessions, does not apply and can be turned off for that chain only. Keep CSRF enabled for the browser chain. Pick the model in session versus JWT. Scoping the exception with a separate chain is the correct response to "CSRF breaks the API", not disabling it for the whole application.

Custom filters

java
http.addFilterBefore(new RequestIdFilter(), UsernamePasswordAuthenticationFilter.class);

Position matters, because a filter sees the request in the state earlier filters left it. A filter placed before authentication sees an anonymous request, and one placed after sees the authenticated user. Set logging.level.org.springframework.security=DEBUG to print the whole chain order for each request, which settles most disputes about where a filter runs. Avoid registering the same filter as a bean as well as in the chain, or Spring Boot adds it to the servlet filter chain a second time.

Exception handling

java
http.exceptionHandling(e -> e
    .authenticationEntryPoint((req, res, ex) -> res.sendError(401))
    .accessDeniedHandler((req, res, ex) -> res.sendError(403)));

The entry point answers unauthenticated requests and the access denied handler answers authenticated ones that lack permission. For APIs, return a JSON problem body instead of a redirect to a login page, since a client cannot follow a redirect to an HTML form usefully. The distinction between the two outcomes is explained in authentication versus authorization.

Test the rules

java
@WebMvcTest
@Import(SecurityConfig.class)
class SecurityRulesTest {

    @Autowired MockMvc mvc;

    @Test
    void adminNeedsRole() throws Exception {
        mvc.perform(get("/admin/users")).andExpect(status().is3xxRedirection());
        mvc.perform(get("/admin/users").with(user("bob").roles("USER"))).andExpect(status().isForbidden());
        mvc.perform(get("/admin/users").with(user("amy").roles("ADMIN"))).andExpect(status().isOk());
    }
}

The test pins the matrix of anonymous, wrong role and right role for one route. Repeat the pattern for each rule that matters, and for a public route that must stay public. A regression in security configuration is invisible in normal use and costly in production, so these tests are among the best value in the suite.

Troubleshooting

A rule that does not apply usually has the wrong order or the wrong matcher. Use the debug log to see which chain handled the request and which rule matched. A POST that fails with 403 despite a successful login is often CSRF, see that fix. A request that loops through the login page may come from a login page that itself requires authentication.

Common mistakes

Ordering rules from general to specific, so anyRequest().authenticated() swallows a later permitAll, is the first. Forgetting that requestMatchers("/api/**") does not match /api itself, so add both when needed, is the second. Disabling CSRF for a whole application because one API needs it is the third. And putting secrets, such as the persistent-login key, in source instead of configuration is the fourth. Reading one request's debug lines is the fastest way to learn what the chain does, and it explains why a custom filter placed after the authentication filter never sees an anonymous user.

Method security as the second line

URL rules decide who may reach an endpoint. Method security decides who may call a service method, regardless of how it was reached. Add @EnableMethodSecurity and put @PreAuthorize on service methods that change data, so that a new controller, a message listener or a scheduled job gets the same protection automatically. The two layers should agree, and tests should cover both. A route that is open at the URL level but guarded at the method level fails safe, while the reverse leaves a hole.

Keeping the configuration readable

A chain with thirty rules is hard to review. Group the matchers by area into small methods, name them, and keep public paths in a list constant. For many chains, put each in its own configuration class. Add a short comment above each non-obvious rule saying why it exists, for example "health check for the load balancer". A security configuration is read mostly by reviewers and auditors, and the comments are for them.

Headers and session settings worth reviewing

Spring Security adds sensible response headers by default: X-Content-Type-Options, cache control for authenticated pages and X-Frame-Options. Review the content security policy against what the pages load, and tighten it. For sessions, set the cookie to Secure and HttpOnly and choose a SameSite value in the server configuration, and rotate the session id on login, which the framework does by default through session fixation protection.

When a chain is not the whole story

Applications behind a gateway that handles all authentication may still want method security internally, because a gateway bypass would otherwise leave everything open. The references are the Spring Security Java configuration chapter and the HttpSecurity Javadoc.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.