Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Filter Chain and Configuration

Writing Custom Security Filters

Write your own servlet filter for Spring Security, place it with addFilterBefore and addFilterAfter, and learn how an API-key filter fits into the chain.

Spring Security ships filters for form login, Basic auth, CSRF and more, but real systems always have one special case: an API key in a header, a signed webhook, a tenant id that must be validated before anything else. For those you write your own filter and place it at the right spot in the chain.

This lesson shows the anatomy of a security filter, the placement methods addFilterBefore, addFilterAfter and addFilterAt, and the rules that keep a custom filter safe. The real Spring classes cannot run on this site, so the real code is read-only, and the runnable examples are small Java stand-ins that model the same ideas.

The anatomy of a security filter

A filter is a normal servlet Filter. The convenient base class is OncePerRequestFilter, which guarantees one execution per request even when the request is forwarded internally:

Java
public class ApiKeyFilter extends OncePerRequestFilter {

    private final ApiKeyService keys;

    public ApiKeyFilter(ApiKeyService keys) {
        this.keys = keys;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String key = request.getHeader("X-Api-Key");
        if (key != null) {
            keys.find(key).ifPresent(client -> {
                var auth = UsernamePasswordAuthenticationToken.authenticated(
                        client.name(), null, client.authorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
            });
        }
        chain.doFilter(request, response);   // always continue
    }
}

Three habits are visible here:

  1. Authenticate, do not authorize. The filter only answers "who is this?". It puts an Authentication into the SecurityContext. The later AuthorizationFilter decides whether that identity may access the URL.
  2. Always call chain.doFilter. If no key is present, you simply continue. An anonymous request is rejected later, by the authorization rules, with the right status code and entry point.
  3. Never trust the filter's order by accident. Register it at an explicit position.

Placing the filter

Java
@Bean
SecurityFilterChain api(HttpSecurity http, ApiKeyService keys) throws Exception {
    http
        .securityMatcher("/api/**")
        .addFilterBefore(new ApiKeyFilter(keys), UsernamePasswordAuthenticationFilter.class)
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .csrf(csrf -> csrf.disable());
    return http.build();
}
Method Meaning
addFilterBefore(f, X.class) Run f immediately before the built-in filter X
addFilterAfter(f, X.class) Run f immediately after X
addFilterAt(f, X.class) Take the same position as X (the order between the two is not defined, so avoid it unless you replace X)

The anchor class tells Spring Security the numeric position. An authentication filter usually goes before UsernamePasswordAuthenticationFilter (or AuthorizationFilter for pre-checks), so that the identity exists before authorization looks at it. A filter that only logs or decorates the response can sit after the ExceptionTranslationFilter.

Do not declare your filter as a plain @Component bean in a Spring Boot application. Boot registers every Filter bean with the servlet container as well, so the filter would run twice: once in the container's chain and once inside the security chain. Create it with new inside the configuration (as above) or add a FilterRegistrationBean that disables registration.

A stand-in chain you can run

The first example models the filter chain as a list of small steps. Each step may stop the request or continue. The API key filter is inserted before the authorization step. Watch what changes when it is moved after it.

Java Filter order decides whether the key is seen (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line is the classic bug: the key is valid, but the authorization step runs first, so the client is rejected. Placement is part of the logic.

Keys must be compared safely

A key lookup is a secret comparison. Two rules:

  • Store only a hash of each key (SHA-256 is enough for random 32-byte keys; they are not low-entropy passwords) and hash the incoming key before comparing.
  • Compare with a constant-time function such as MessageDigest.isEqual, so response time does not leak how many leading bytes matched.
Java A hashed API-key store with constant-time comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In a real project the store is a database table with a unique index on the hash column, so the lookup is an indexed query rather than a loop.

Reading the request body in a filter

Filters often need the body (for example to verify a signature, as in multiple filter chains). The servlet input stream can be read only once, so wrap the request in a ContentCachingRequestWrapper or a custom wrapper that stores the bytes, and pass the wrapper down the chain. Always cap the size you read; an unbounded read is a denial-of-service gift.

Exceptions in custom filters

An exception thrown inside your filter does not get the pretty handling that controller exceptions enjoy, because @ControllerAdvice belongs to Spring MVC and your filter runs before it. Two choices:

  • If the filter is placed after ExceptionTranslationFilter, throw an AuthenticationException or AccessDeniedException and let that filter translate it through the entry point and access-denied handler (see exception handling).
  • Otherwise write the response yourself (response.sendError(401) or JSON) and return without calling chain.doFilter.

Debugging the order

To see the chain with your filter in it, enable startup logging:

PROPERTIES
logging.level.org.springframework.security=DEBUG

or inject FilterChainProxy and print getFilterChains() in a test. The log line "Securing GET /api/orders" followed by one line per filter ("Invoking ApiKeyFilter (3/12)") shows the true order.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a custom authentication filter always call chain.doFilter even when no credentials are present?

    The filter only identifies the caller. Rejecting anonymous requests is the job of AuthorizationFilter and the entry point.
  2. 2. Which call places a filter right before the form-login filter?

    addFilterBefore takes the filter and an anchor class from the built-in chain.
  3. 3. What goes wrong if you annotate your security filter with @Component in a Spring Boot application?

    Boot registers all Filter beans with the container. Create the filter with new inside the security configuration, or disable the registration.
  4. 4. How should API keys be stored?

    A hash means a stolen database does not reveal usable keys, and constant-time comparison avoids timing leaks.

Summary

  • A custom security filter extends OncePerRequestFilter, authenticates the caller, stores an Authentication and always continues the chain.
  • Position it explicitly with addFilterBefore, addFilterAfter or addFilterAt; the order decides whether other filters see its result.
  • Do not make the filter a Boot @Component; create it inside the security configuration.
  • Hash stored API keys and compare secrets in constant time.
  • Cache request bodies with a wrapper and limit their size; handle errors by throwing security exceptions or writing the response yourself.

Next: Exception handling: entry points and access-denied handlers