Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 45

    Security Filters

    Spring Security is a filter chain.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Identify whether a built-in mechanism already covers the need (JWT resource server).
    2. If custom, implement OncePerRequestFilter and keep it side-effect light.
    3. Register it on the SecurityFilterChain with an explicit relative position.
    4. Integration-test missing, invalid, and valid header cases.

    Informative example

    Partner API key filter registered on the chain.

    java
    public class PartnerApiKeyFilter extends OncePerRequestFilter {
    private final PartnerKeyService keys;
    public PartnerApiKeyFilter(PartnerKeyService keys) {
    this.keys = keys;
    }
    @Override
    protected 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);
    }
    }
    @Bean
    SecurityFilterChain 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 SecurityFilterChain bean.

    Common mistakes

    • Forgetting to invoke chain.doFilter and hanging requests.
    • Using javax.servlet imports on Boot 3 — use jakarta.servlet.
    • Registering the same filter as both a @Component servlet filter and via HttpSecurity, causing double execution.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy extend OncePerRequestFilter?+

    Answer

    It ensures the logic runs once per request, avoiding duplicate work on forwarded dispatches.
    2IntermediateQuestionHow do you position a custom filter?+

    Answer

    Use HttpSecurity.addFilterBefore/After/At relative to a known Security filter class.
    3BeginnerQuestionjavax vs jakarta servlet on Boot 3?+

    Answer

    Boot 3 uses Jakarta EE packages — 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.

    Ready to mark this lesson complete?Track your journey across the entire course.