addFilterAt adds a custom filter to the position associated with another filter class in Spring Security’s filter chain. For example, a static-key authentication filter can occupy the position associated with BasicAuthenticationFilter. section 5.4
Use the method with these constraints:
- Passing BasicAuthenticationFilter.class identifies its ordering position; it does not replace a filter instance. section 5.4
- Multiple filters can share the position, but Spring Security does not guarantee their order. section 5.4
- Avoid adding unnecessary filters at the same position so the chain remains understandable and maintainable. section 5.4
Static-key authentication
Define StaticKeyAuthenticationFilter to compare the Authorization header with a configured key, forward matching requests, and return 401 for mismatches. Register it with http.addFilterAt(filter, BasicAuthenticationFilter.class). Omit httpBasic() when the built-in BasicAuthenticationFilter should not be added, then test with curl. section 5.4
Figure 5.13 We add our custom authentication filter at the location where the class BasicAuthenticationFilter would have been if we were using HTTP Basic as an authentication method. This means our custom filter has the same ordering value.
Visualizes the custom filter sharing BasicAuthenticationFilter’s ordering value. section 5.4
