Security filter chain
What you will learn
Security filters intercept requests before controllers. Separate the chain that handles a request from the policy that permits its actions.
- Trace authentication and authorization through servlet filters.
- Distinguish securityMatcher from requestMatchers.
- Design ordered chains with a deny-by-default fallback.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Spring Security examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
First matching chain model
public class Main { static String chain(String path){return path.startsWith("/api/")?"api":"fallback";} public static void main(String[] args) {for(String path:java.util.List.of("/api/tenants/north/report","/browser/home","/unknown")) System.out.println(path+" -> "+chain(path)); }}Expected output:
/api/tenants/north/report -> api/browser/home -> fallback/unknown -> fallbackThis is a simplified prefix model, not Spring path matching; the fallback still evaluates authorization.
Request flow
A servlet container delegates to Spring Security through DelegatingFilterProxy and FilterChainProxy. The latter chooses the first matching SecurityFilterChain; filters in that chain load context, establish identity, protect against exploits and check authorization before the controller. ExceptionTranslationFilter bridges authentication or access denial into the configured entry point or access-denied handler. A resource server typically answers missing or invalid bearer credentials with 401 and a challenge, and an authenticated caller without required authority with 403. Browser form login may redirect instead. A CSRF rejection can also be 403 before authorization. A SecurityContextHolder associates authentication with the current execution; framework filters manage cleanup. Do not propagate context into arbitrary thread pools by assuming ordinary thread-local state follows a task.
Match the chain before its rules
securityMatcher selects the entire chain. Inside it, authorizeHttpRequests evaluates requestMatchers in order and applies the first matching rule. A more general rule placed first can shadow a restrictive one. @Order(1) in the lab selects /api/**, and the browser chain has no securityMatcher so it covers remaining requests. Both end with denyAll. Without a matching chain, Spring Security does not protect that request. The current DSL exposes SecurityFilterChain beans and lambda customization; older WebSecurityConfigurerAdapter examples must not be copied into Security 7. permitAll allows an endpoint through authorization but does not disable other filters. The API is GET-only and retains default CSRF protection; it has no browser form or Basic authentication.
Status decision model
public class Main { static int status(boolean authenticated,boolean allowed){return !authenticated?401:allowed?200:403;} public static void main(String[] args) {System.out.println(status(false,false));System.out.println(status(true,false));System.out.println(status(true,true)); }}Expected output:
401403200This models a protected bearer GET, not browser redirects, error dispatch or CSRF.
Ordered resource-server chain
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/main/java/example/tenant/ApiSecurity.java; use the companion lab README.
package example.tenant;import java.util.List;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;import org.springframework.http.HttpMethod;import org.springframework.web.cors.*;@Configuration@EnableMethodSecuritypublic class ApiSecurity { @Bean @Order(1) SecurityFilterChain api(HttpSecurity http) throws Exception { return http.securityMatcher("/api/**") .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .requestCache(c -> c.disable()) .cors(c -> c.configurationSource(apiCors())) .authorizeHttpRequests(a -> a .requestMatchers(HttpMethod.GET,"/api/tenants/*/report").hasAuthority("SCOPE_report.read") .anyRequest().denyAll()) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) .build(); // GET-only API; leave CSRF protection enabled. } private CorsConfigurationSource apiCors() { var config = new CorsConfiguration(); config.setAllowedOrigins(List.of("https://ui.example.invalid")); config.setAllowedMethods(List.of("GET")); config.setAllowedHeaders(List.of("Authorization")); config.setAllowCredentials(false); var source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/api/**",config); return source; }}Predicted behavior: GET report requests require SCOPE_report.read; unrelated API routes are denied.
The resource-server authentication mechanism is separate from the browser chain.
Controller boundary
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/main/java/example/tenant/TenantController.java; use the companion lab README.
package example.tenant;import org.springframework.web.bind.annotation.*;@RestControllerpublic class TenantController { private final ReportService reports; public TenantController(ReportService reports) { this.reports=reports; } @GetMapping("/api/tenants/{tenant}/report") String report(@PathVariable("tenant") String tenant) { return reports.report(tenant); } @GetMapping("/browser/home") String home() { return "lab home"; } @PostMapping("/browser/note") String note() { return "simulated save"; }}Predicted behavior: Only a successful filter-chain and service authorization reaches the report response.
The note endpoint simulates a mutation; no stored data.
Common mistakes
Do not leave gaps between chain matchers, put broad permitAll before narrower rules, or rely on a controller annotation as the only security boundary. Do not assume all denials are 403 or all anonymous requests redirect.
Practice
Model a protected bearer GET: for unauthenticated, authenticated without scope, and authenticated with scope print 401, 403 and 200 respectively; add unknown routes as denied.
Expected output:
401403200403Compare with the manual review criteria.
Official reading: Architecture · Config · Authorization. Spring execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security filter chain — knowledge check
Spring Security identity and authorization reasoning.
Which component chooses the first matching security chain?
What does securityMatcher select?
What is a useful final rule?
What does a protected bearer GET without credentials typically return?
What does permitAll do?