liveBook · Manning

addFilterAt

As explained in Spring Security in Action, Second Edition

addFilterAt is a Spring Security HttpSecurity method that inserts a filter at the position associated with another filter class.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains configuration and ordering behavior, while stopping short of deeper filter-chain internals.
Examples
Uses a static-key authentication filter, Authorization headers, a SecurityFilterChain bean, and curl requests.
What it assumes
Assumes basic Java and Spring Security configuration, including SecurityFilterChain and filter-chain concepts.
What you can do after
Apply it via HttpSecurity to insert a custom filter at a known filter position and test accepted or rejected requests.
How it connects
Connects custom filters with filter chains, BasicAuthenticationFilter, and HTTP Basic configuration.

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.