00:00

Custom Security Filter in Spring Security

Last updated:

A custom security filter is your own servlet filter placed at a chosen position in the Spring Security filter chain. It is the extension point for anything the built-in filters do not cover: a proprietary authentication header, an API key, a tenant check, or request auditing that needs to know the authenticated user.

This tutorial writes a filter that authenticates refrigerated-truck sensors by an API key, while human operators keep using HTTP Basic. It covers where to insert the filter, how to set the security context correctly, how to keep CSRF protection meaningful, and the registration mistake that makes many custom filters run twice.

1. What Is a Custom Security Filter?

It is a class implementing jakarta.servlet.Filter, almost always by extending Spring's OncePerRequestFilter, which guarantees a single execution per request. You add it to a SecurityFilterChain relative to a built-in filter with addFilterBefore, addFilterAfter or addFilterAt. Inside, it inspects the request and either passes it on with chain.doFilter(...) or writes a response and stops.

An authentication filter has one more duty: on success it stores an authenticated Authentication in the SecurityContextHolder, so that AuthorizationFilter and method security see the caller. The standard order of the built-in filters is shown in Spring Security filter chain.

2. Why Write a Custom Filter?

  • Non-standard credentials. Devices, partners or legacy systems that send an API key or a signed header.
  • Cross-cutting checks that need security context. A tenant header that must match the user's tenant, or an audit log entry with the user name.
  • Early rejection. Blocking a request before it reaches controllers, for example a request from a revoked device.

Before writing one, check whether a built-in option fits: oauth2ResourceServer() for bearer tokens, x509() for client certificates, or a custom AuthenticationProvider behind an existing filter.

3. How the Filter Fits into the Chain

Position of the custom API key filterThe DeviceApiKeyFilter is inserted before BasicAuthenticationFilter. Requests with an X-Device-Key header are authenticated by it; requests without the header pass through to Basic authentication. AuthorizationFilter then applies the rules to whoever was authenticated. CsrfFilter skipped for device key requests DeviceApiKeyFilter X-Device-Key present? Valid key ROLE_DEVICE set No header continue Invalid key 401, stop BasicAuthentication Filter: operators AuthorizationFilter URL rules
Figure 1: the custom filter runs before Basic authentication; whichever filter authenticates, AuthorizationFilter decides last.
MethodInserts the filter
addFilterBefore(filter, BasicAuthenticationFilter.class)Immediately before the given filter
addFilterAfter(filter, AuthorizationFilter.class)Immediately after it (here: after access is granted)
addFilterAt(filter, SomeFilter.class)At the same position; both filters stay in the chain

Authentication filters belong before AuthorizationFilter, usually before UsernamePasswordAuthenticationFilter or BasicAuthenticationFilter. Filters that need to know the final decision, such as auditing, go after AuthorizationFilter.

4. A Complete Example: API Keys for Cold-Chain Sensors

Each refrigerated truck has a sensor that posts temperature readings with its own key in the X-Device-Key header. Operators log in with HTTP Basic to view the dashboard. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.coldchain;

import java.io.IOException;
import java.util.List;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.web.filter.OncePerRequestFilter;

public class DeviceApiKeyFilter extends OncePerRequestFilter {

    static final String HEADER = "X-Device-Key";

    private final DeviceRegistry registry;
    private final SecurityContextHolderStrategy holder = SecurityContextHolder.getContextHolderStrategy();

    public DeviceApiKeyFilter(DeviceRegistry registry) {
        this.registry = registry;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String key = request.getHeader(HEADER);
        if (key == null) {
            chain.doFilter(request, response);          // not a device: let other filters decide
            return;
        }
        String device = registry.deviceForKey(key).orElse(null);
        if (device == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.getWriter().write("{\"error\":\"invalid device key\"}");
            return;                                     // stop the chain
        }
        SecurityContext context = holder.createEmptyContext();
        context.setAuthentication(UsernamePasswordAuthenticationToken.authenticated(
            device, null, List.of(new SimpleGrantedAuthority("ROLE_DEVICE"))));
        holder.setContext(context);                     // valid for this request only
        chain.doFilter(request, response);
    }
}

5. Step-by-Step Code Explanation

  1. No header, no opinion. Requests without X-Device-Key pass straight through, so operators continue to use HTTP Basic. A filter that rejected them would break every other login mechanism.
  2. Invalid key, stop. A wrong key gets a 401 and the chain is not continued. Returning without calling chain.doFilter is how a filter ends a request.
  3. Valid key, set the context. The filter creates an authenticated token with ROLE_DEVICE and sets it through SecurityContextHolderStrategy. With a stateless chain nothing is saved, so the next request must send its key again.
  4. Keys are hashed. API keys are long random values, so a fast hash such as SHA-256 is appropriate (unlike user passwords, which need BCrypt). MessageDigest.isEqual compares in constant time.
  5. Placement. addFilterBefore(..., BasicAuthenticationFilter.class) puts the filter among the authentication filters, before AuthorizationFilter checks the rules.
  6. CSRF exemption by header. Only requests carrying the device header skip CSRF. A malicious web page cannot add that header to a cross-site request without a CORS preflight that the API would refuse.
  7. Not a bean. The filter is created with new. If it were a @Component, Spring Boot would also register it with the servlet container, and it would run twice: once outside the security chain and once inside.

6. Expected Output

Terminal
$ curl -X POST localhost:8080/api/telemetry -H 'X-Device-Key: dk_cold01_9f2b7c41e8a64d0f' -H 'Content-Type: application/json' -d '{"celsius":3.8}'
HTTP/1.1 200
{"stored":true,"celsius":3.8,"device":"truck-cold-01"}

$ curl -X POST localhost:8080/api/telemetry -H 'X-Device-Key: dk_guessed_key' -H 'Content-Type: application/json' -d '{"celsius":3.8}'
HTTP/1.1 401
{"error":"invalid device key"}

$ curl localhost:8080/api/dashboard -H 'X-Device-Key: dk_cold01_9f2b7c41e8a64d0f'
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:10.328Z","status":403,"error":"Forbidden","path":"/api/dashboard"}

$ curl -u kavya:kavya-pass localhost:8080/api/dashboard
HTTP/1.1 200
{"operator":"kavya","truck-cold-01":"3.8 C, within range"}

$ curl localhost:8080/api/dashboard
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
{"timestamp":"2026-11-18T12:14:10.466Z","status":401,"error":"Unauthorized","path":"/api/dashboard"}

The sensor's reading is accepted and attributed to truck-cold-01. A guessed key is rejected by the custom filter before any other code runs. A valid device key does not open the operator dashboard, because ROLE_DEVICE is not ROLE_OPERATOR: the custom filter authenticates, but AuthorizationFilter still decides. Kavya reaches the dashboard through Basic authentication, and a request with no credentials receives the usual Basic challenge. With DEBUG logging for DefaultSecurityFilterChain, startup confirms the filter's position:

Terminal
Will secure any request with filters: DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, DeviceApiKeyFilter, BasicAuthenticationFilter, RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, AuthorizationFilter

7. Advantages and Limitations

AdvantagesLimitations
Supports any credential or check you needYou own correctness: constant-time comparison, error responses, logging
Integrates with authorization, method security and error handlingWrong placement silently weakens security
Precise CSRF and session behaviour per request typeBypasses the AuthenticationManager unless you delegate to it
Small and easy to unit testEasy to register twice by accident

8. Common Mistakes and Best Practices

  • Double execution. Do not make the filter a bean, or disable its servlet registration with a FilterRegistrationBean whose setEnabled(false) is called.
  • Rejecting requests the filter does not understand. Pass them on and let other mechanisms try.
  • Placing an authentication filter after AuthorizationFilter. The rules would be checked before the user is known.
  • Plain equals on secrets. Compare hashes with MessageDigest.isEqual.
  • Consider delegation for complex logic. For multi-step checks, convert the header into a token and call an AuthenticationManager; Spring Security's generic AuthenticationFilter with an AuthenticationConverter does exactly that.

9. Summary

  • A custom security filter extends OncePerRequestFilter and is added with addFilterBefore, addFilterAfter or addFilterAt.
  • Authentication filters run before AuthorizationFilter and set an authenticated Authentication in the security context.
  • Pass through requests you do not handle; stop the chain only for invalid credentials.
  • Do not register the filter as a bean, or it may run twice.
  • Exempt from CSRF only requests that carry credentials browsers cannot add on their own.

10. References