Security Filters
Spring Security is a filter chain.
Introduction
Spring Security is a filter chain. Each request passes filters for CORS, CSRF, authentication, authorization, and more before Orders controllers run. Understanding order is essential when you add JWT, API keys, or audit logic.
Custom filters usually extend OncePerRequestFilter and register with http.addFilterBefore/After/At relative to a known Security filter class.
Prefer the built-in resource-server JWT filters when they fit. Write custom filters for cross-cutting concerns the DSL does not cover — correlation ids, partner API keys, or signed request headers.
Filters must be careful: do not swallow exceptions incorrectly, and always continue the chain when appropriate so authorization still runs.
Purpose of this lesson
Place custom security filters correctly on the Security 6 SecurityFilterChain for Orders cross-cutting auth concerns.
Understanding the topic
Order matters: wrong placement skips authentication or runs twice.
- SecurityFilterChain: ordered list wrapping the servlet filter chain.
- OncePerRequestFilter: base class avoiding duplicate work on dispatches.
- addFilterBefore: run ahead of a landmark filter (e.g. username/password).
- SecurityContext: filters populate Authentication for downstream authorization.
- Fail closed: invalid credentials should not silently continue as anonymous unless intended.
Step-by-step explanation
- Identify whether a built-in mechanism already covers the need (JWT resource server).
- If custom, implement
OncePerRequestFilterand keep it side-effect light. - Register it on the
SecurityFilterChainwith an explicit relative position. - Integration-test missing, invalid, and valid header cases.
Informative example
Partner API key filter registered on the chain.
public class PartnerApiKeyFilter extends OncePerRequestFilter {private final PartnerKeyService keys;public PartnerApiKeyFilter(PartnerKeyService keys) {this.keys = keys;}@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws ServletException, IOException {String key = request.getHeader("X-Api-Key");if (key != null && keys.isValid(key)) {var auth = new UsernamePasswordAuthenticationToken(keys.partnerName(key),null,AuthorityUtils.createAuthorityList("ROLE_PARTNER"));SecurityContextHolder.getContext().setAuthentication(auth);}chain.doFilter(request, response);}}@BeanSecurityFilterChain api(HttpSecurity http, PartnerApiKeyFilter partnerFilter) throws Exception {return http.csrf(csrf -> csrf.disable()).sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).addFilterBefore(partnerFilter, UsernamePasswordAuthenticationFilter.class).authorizeHttpRequests(auth -> auth.anyRequest().authenticated()).build();}
Real-world use
A B2B inventory partner pushes stock updates into TechLearningPRO Orders. They authenticate with rotating API keys rather than end-user JWTs. A dedicated filter validates X-Api-Key, sets ROLE_PARTNER, and leaves customer JWT routes on the resource-server filter — two authentication styles, one chain design.
Security implications
Filters are a privileged choke point.
- Do not log full API keys or Authorization headers.
- Reject empty keys explicitly when the path requires them.
- Ensure authorization rules still apply after you set Authentication.
Best practices
- Prefer Security DSL features before custom filters.
- Keep filters focused; put business rules in services.
- Document filter order next to the
SecurityFilterChainbean.
Common mistakes
- Forgetting to invoke
chain.doFilterand hanging requests. - Using
javax.servletimports on Boot 3 — usejakarta.servlet. - Registering the same filter as both a
@Componentservlet filter and viaHttpSecurity, causing double execution.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy extend OncePerRequestFilter?+
Answer
2IntermediateQuestionHow do you position a custom filter?+
Answer
HttpSecurity.addFilterBefore/After/At relative to a known Security filter class.3BeginnerQuestionjavax vs jakarta servlet on Boot 3?+
Answer
jakarta.servlet.*, not javax.servlet.*.Hands-on exercise
Lab. Add PartnerApiKeyFilter for /api/partner/**. Call with a placeholder key header and without; confirm 200 vs 401/403. Verify jakarta.servlet imports only.
Summary
Filters implement Orders authentication plumbing. Next: OAuth2 basics for delegated login and resource servers.