Custom Security Filter in Spring Security
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
| Method | Inserts 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);
}
}
package com.javabytechie.coldchain;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Component;
// Stores only SHA-256 hashes of the random device keys
@Component
public class DeviceRegistry {
private final Map<String, String> deviceByKeyHash = Map.of(
sha256("dk_cold01_9f2b7c41e8a64d0f"), "truck-cold-01"); // demo key
public Optional<String> deviceForKey(String key) {
byte[] presented = HexFormat.of().parseHex(sha256(key));
return deviceByKeyHash.entrySet().stream()
.filter(e -> MessageDigest.isEqual(HexFormat.of().parseHex(e.getKey()), presented))
.map(Map.Entry::getValue)
.findFirst();
}
static String sha256(String value) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
package com.javabytechie.coldchain;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http, DeviceRegistry registry) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.requestMatchers(HttpMethod.POST, "/api/telemetry").hasRole("DEVICE")
.requestMatchers("/api/dashboard").hasRole("OPERATOR")
.anyRequest().authenticated())
// Not a @Bean or @Component, so Spring Boot does not also register it as a servlet filter
.addFilterBefore(new DeviceApiKeyFilter(registry), BasicAuthenticationFilter.class)
.httpBasic(Customizer.withDefaults())
// Browsers cannot send a custom header cross-site without CORS permission
.csrf(csrf -> csrf.ignoringRequestMatchers(
request -> request.getHeader(DeviceApiKeyFilter.HEADER) != null))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
UserDetailsService users(PasswordEncoder encoder) {
// Demo operator only
return new InMemoryUserDetailsManager(
User.withUsername("kavya").password(encoder.encode("kavya-pass")).roles("OPERATOR").build());
}
}
package com.javabytechie.coldchain;
import java.security.Principal;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TelemetryController {
@PostMapping("/api/telemetry")
public Map<String, Object> record(@RequestBody Map<String, Double> reading, Principal device) {
return Map.of("device", device.getName(), "celsius", reading.get("celsius"), "stored", true);
}
@GetMapping("/api/dashboard")
public Map<String, String> dashboard(Principal operator) {
return Map.of("operator", operator.getName(), "truck-cold-01", "3.8 C, within range");
}
}
package com.javabytechie.coldchain;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ColdChainApplication {
public static void main(String[] args) {
SpringApplication.run(ColdChainApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- No header, no opinion. Requests without
X-Device-Keypass straight through, so operators continue to use HTTP Basic. A filter that rejected them would break every other login mechanism. - Invalid key, stop. A wrong key gets a 401 and the chain is not continued. Returning without calling
chain.doFilteris how a filter ends a request. - Valid key, set the context. The filter creates an authenticated token with
ROLE_DEVICEand sets it throughSecurityContextHolderStrategy. With a stateless chain nothing is saved, so the next request must send its key again. - 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.isEqualcompares in constant time. - Placement.
addFilterBefore(..., BasicAuthenticationFilter.class)puts the filter among the authentication filters, beforeAuthorizationFilterchecks the rules. - 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.
- 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
$ 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:
Will secure any request with filters: DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, DeviceApiKeyFilter, BasicAuthenticationFilter, RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, AuthorizationFilter
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Supports any credential or check you need | You own correctness: constant-time comparison, error responses, logging |
| Integrates with authorization, method security and error handling | Wrong placement silently weakens security |
| Precise CSRF and session behaviour per request type | Bypasses the AuthenticationManager unless you delegate to it |
| Small and easy to unit test | Easy 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
FilterRegistrationBeanwhosesetEnabled(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
equalson secrets. Compare hashes withMessageDigest.isEqual. - Consider delegation for complex logic. For multi-step checks, convert the header into a token and call an
AuthenticationManager; Spring Security's genericAuthenticationFilterwith anAuthenticationConverterdoes exactly that.
9. Summary
- A custom security filter extends
OncePerRequestFilterand is added withaddFilterBefore,addFilterAfteroraddFilterAt. - Authentication filters run before
AuthorizationFilterand set an authenticatedAuthenticationin 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
Frequently Asked Questions (FAQ)
Q1. How do I add a custom filter to Spring Security?
Create a class extending OncePerRequestFilter and add it to your SecurityFilterChain with http.addFilterBefore(myFilter, BasicAuthenticationFilter.class) or a similar method.
Q2. Why does my custom filter run twice?
Because it is a Spring bean, so Spring Boot registers it with the servlet container as well as in the security chain. Create it with new or disable its registration with FilterRegistrationBean.setEnabled(false).
Q3. Where should a custom authentication filter be placed?
Before AuthorizationFilter, typically before UsernamePasswordAuthenticationFilter or BasicAuthenticationFilter, so the user is known when access rules are evaluated.
Q4. What is the difference between addFilterBefore and addFilterAt?
addFilterBefore places your filter immediately before the named filter. addFilterAt gives it the same order position; it does not replace the existing filter.
Q5. Should a custom filter call chain.doFilter after a failure?
No. After writing an error response, return without calling chain.doFilter, otherwise the request continues into the application.