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

    Security Filters

    Spring Security is a filter chain.

    Course progress0%
    Focus
    2 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Spring Security is a filter chain. Each request walks through filters in order: CORS → CSRF → authentication → authorization → controller. Adding a custom filter (e.g. for API keys, request signing, audit) is two beans.

    Informative example

    ts
    @Component
    public class ApiKeyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
    throws IOException, ServletException {
    String key = req.getHeader("X-Api-Key");
    if (key != null && apiKeys.isValid(key)) {
    var auth = new ApiKeyAuthentication(key, AuthorityUtils.createAuthorityList("ROLE_SERVICE"));
    SecurityContextHolder.getContext().setAuthentication(auth);
    }
    chain.doFilter(req, res);
    }
    }
    @Bean SecurityFilterChain chain(HttpSecurity http, ApiKeyFilter apiKeyFilter) throws Exception {
    return http
    .addFilterBefore(apiKeyFilter, UsernamePasswordAuthenticationFilter.class)
    .build();
    }
    Ready to mark this lesson complete?Track your journey across the entire course.