Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this quick tutorial, we’ll focus on writing a custom filter for the Spring Security filter chain.

Further reading:

Spring Security – @PreFilter and @PostFilter

Learn how to use the @PreFilter and @PostFilter Spring Security annotations through practical examples.

Introduction to Java Config for Spring Security

A quick and practical guide to Java Config for Spring Security

Spring Boot Security Auto-Configuration

A quick and practical guide to Spring Boot's default Spring Security configuration.

2. Creating the Filter

Spring Security provides a number of filters by default, and these are enough most of the time.

Of course, it’s sometimes necessary to implement new functionality by creating a new filter to use in the chain.

We’ll start by implementing the org.springframework.web.filter.GenericFilterBean.

The GenericFilterBean is a simple javax.servlet.Filter implementation that is Spring-aware.

We only need to implement a single method:

public class CustomFilter extends GenericFilterBean {
    @Override
    public void doFilter(
      ServletRequest request, 
      ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
}

3. Using the Filter in the Security Config

We’re free to choose either XML configuration or Java configuration to wire the filter into the Spring Security configuration.

3.1. Java Configuration

We can register the filter programmatically by creating a SecurityFilterChain bean.

For example, it works with the addFilterAfter method on an HttpSecurity instance:

@Configuration
public class CustomWebSecurityConfigurerAdapter {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.addFilterAfter(
          new CustomFilter(), BasicAuthenticationFilter.class);
        return http.build();
    }
}

There are a couple of possible methods:

3.2. XML Configuration

We can add the filter to the chain using the custom-filter tag and one of these names to specify the position of our filter.

For instance, it can be pointed out by the after attribute:

<http>
    <custom-filter after="BASIC_AUTH_FILTER" ref="myFilter" />
</http>

<beans:bean id="myFilter" class="com.baeldung.security.filter.CustomFilter"/>

Here are all the attributes to specify exactly where to place our filter in the stack:

  • after describes the filter immediately after which a custom filter will be placed in the chain.
  • before defines the filter before which our filter should be placed in the chain.
  • position allows replacing a standard filter in the explicit position by a custom filter.

4. Applying Spring Security Filter Only on Secured Endpoints

Modern applications often serve both public and secured endpoints. Applying a custom Spring Security filter globally can lead to unnecessary processing for public endpoints. To address this, we can target the filter specifically to secured endpoints by using Spring Security’s SecurityFilterChain and RequestMatcher:

@Bean
public SecurityFilterChain securedFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
      authorizationManagerRequestMatcherRegistry.requestMatchers("/secured/**").authenticated())
        .httpBasic(Customizer.withDefaults());
    http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
    return http.build();
}

This configuration ensures that security settings are only applied to endpoints matching /secured/**, as specified by requestMatchers(“/secured/**”).

The addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class) line ensures the custom filter is applied after the BasicAuthenticationFilter, meaning it will execute only after the basic authentication process.

This approach allows for targeted security processing on secured endpoints without affecting public ones. All requests to /secured/** require authentication, as enforced by .authorizeHttpRequests().

By using a custom SecurityFilterChain, we can isolate these security settings, keeping the application’s security modular and efficient. This setup prevents unnecessary overhead on public endpoints and ensures tailored authentication handling for secured paths, such as custom failure responses in the authentication entry point.

5. Conclusion

In this quick article, we created a custom filter and wired that into the Spring Security filter chain.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW