How to Insert Custom Filters into Spring Security’s Filter Chain

This guide explains how to create a custom Spring Security filter, extend GenericFilterBean, and precisely position it within the default filter chain using HttpSecurity’s addFilterBefore, addFilterAfter, or addFilterAt methods, complete with code examples and configuration steps.

Programmer DD
Programmer DD
Programmer DD
How to Insert Custom Filters into Spring Security’s Filter Chain

Problem Statement

When building a Spring Security‑based application you may need to run custom logic at a specific point in the security filter chain, such as before authentication or after CSRF protection.

Default Spring Security Filter Chain

The framework defines a fixed order of filters (e.g., ChannelProcessingFilter, SecurityContextPersistenceFilter, UsernamePasswordAuthenticationFilter, CsrfFilter, etc.). The order is top‑to‑bottom as listed in the official documentation.

Filter order is evaluated from the top of the list to the bottom.

Creating a Custom Filter

A custom filter should extend GenericFilterBean. Below is a minimal example that prints a message and then continues the chain.

public class BeforeLoginFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        System.out.println("This is a filter before UsernamePasswordAuthenticationFilter.");
        // Continue the chain
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

Configuring the Filter Position

In the configure(HttpSecurity http) method you can place the custom filter at the desired location using the three helper methods provided by HttpSecurity.

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/user/**").hasRole("USER")
        .and()
        .formLogin().loginPage("/login").defaultSuccessUrl("/user")
        .and()
        .logout().logoutUrl("/logout").logoutSuccessUrl("/login");

    // Insert BeforeLoginFilter before UsernamePasswordAuthenticationFilter
    http.addFilterBefore(new BeforeLoginFilter(),
                         UsernamePasswordAuthenticationFilter.class);

    // Insert AfterCsrfFilter after CsrfFilter (example of a second custom filter)
    http.addFilterAfter(new AfterCsrfFilter(),
                        CsrfFilter.class);
}

HttpSecurity Helper Methods

addFilterBefore(Filter filter, Class beforeFilter)

– adds filter before the specified beforeFilter in the chain. addFilterAfter(Filter filter, Class afterFilter) – adds filter after the specified afterFilter. addFilterAt(Filter filter, Class atFilter) – adds filter at the same position as atFilter without replacing the existing filter.

By placing breakpoints inside each filter’s doFilter method you can verify the execution order and ensure the custom filter runs at the intended stage.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCustom Filterspring-securityHttpSecurity
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.