BackendBench
Coffee

Unravel โ€บ Java concepts โ€บ Security

Spring

Spring Security filter chain and authorization rules

Spring Security is a chain of servlet filters in front of your controllers.

Learn these first

At a glance

Mental model

Airport security: a fixed sequence of checkpoints.

What happens, in order
  1. 1A SecurityFilterChain bean configures the rules: http.authorizeHttpRequests(a -> a.requestMatchers("/public/**").permitAll().requestMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated())Rules are checked in order; the first match wins.
  2. 2Authentication filters read credentials (a form, a Basic header, a Bearer token) and create an Authentication objectA custom filter is added with addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class).
  3. 3The AuthenticationManager asks AuthenticationProviders to verify credentials, usually through a UserDetailsService and a PasswordEncoderOn success the SecurityContext holds the user for the rest of the request.
  4. 4Failures are routed: a missing or invalid login gives the AuthenticationEntryPoint (401 or redirect to login), a logged-in user without rights gives the AccessDeniedHandler (403)
Remember
Watch out
Wrong rule order exposing endpointsRelying only on URL rules without ownership checksDisabling CSRF on cookie-based appsCustom filter at the wrong position in the chain
Example (highlighted lines explain it)
@Beanpublic SecurityFilterChain api(HttpSecurity http, JwtAuthFilter jwtFilter) throws Exception {    http.csrf(csrf -> csrf.disable())        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))        .authorizeHttpRequests(a -> a            .requestMatchers("/auth/**", "/actuator/health").permitAll()            .requestMatchers("/admin/**").hasRole("ADMIN")            .anyRequest().authenticated())        .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);    return http.build();}
  1. line 4 uses sessionManagement, the core of Spring Security filter chain and authorization rules
  2. line 5 uses authorizeHttpRequests, the core of Spring Security filter chain and authorization rules
  3. line 6 uses requestMatchers, the core of Spring Security filter chain and authorization rules
  4. line 7 uses requestMatchers, the core of Spring Security filter chain and authorization rules
  5. line 8 uses anyRequest, the core of Spring Security filter chain and authorization rules
  6. line 9 uses addFilterBefore, the core of Spring Security filter chain and authorization rules
Read the full explanation (about 2 min)

Spring Security is a chain of servlet filters in front of your controllers. Each request is authenticated (who are you?) and then authorized (are you allowed?) according to rules you define in a SecurityFilterChain bean.

A mental model

Airport security: a fixed sequence of checkpoints. Passport control (authentication filters) decides who you are, then the gate agent (authorization) checks if your ticket allows this flight, and a rejected passenger is sent to a specific desk (entry point).

How it works

A SecurityFilterChain bean configures the rules: http.authorizeHttpRequests(a -> a.requestMatchers("/public/**").permitAll().requestMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated()). Rules are checked in order; the first match wins.

Authentication filters read credentials (a form, a Basic header, a Bearer token) and create an Authentication object. A custom filter is added with addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class).

The AuthenticationManager asks AuthenticationProviders to verify credentials, usually through a UserDetailsService and a PasswordEncoder. On success the SecurityContext holds the user for the rest of the request.

Failures are routed: a missing or invalid login gives the AuthenticationEntryPoint (401 or redirect to login), a logged-in user without rights gives the AccessDeniedHandler (403).

Going deeper

Order and specificity of rules matter. A broad permitAll() placed before a specific rule silently exposes it. End with anyRequest().authenticated() (deny by default) rather than permitAll().

For stateless APIs set SessionCreationPolicy.STATELESS and disable CSRF only when authentication is not cookie based. Browsers sending cookies need CSRF protection.

URL rules alone are not enough. Add method security (@PreAuthorize) and check ownership of the data in services (order.customerId == currentUser); otherwise any logged-in user can read anyone else data by changing an id (IDOR).

Under the hood

The DelegatingFilterProxy forwards each servlet request to FilterChainProxy, which picks the first matching SecurityFilterChain and runs its ordered filters (CORS, CSRF, logout, authentication filters, exception translation, authorization). The SecurityContextHolder keeps the context in a thread-local for the duration of the request and clears it afterwards.

Common mistakes

  • Wrong rule order exposing endpoints.
  • Relying only on URL rules without ownership checks.
  • Disabling CSRF on cookie-based apps.
  • Custom filter at the wrong position in the chain.

How Unravel recognises it

When you paste code, Unravel looks for these signs of spring security filter chain and authorization rules. Spotting them yourself is a good habit when you read unfamiliar code:

Part of a learning path

Related concepts

Builds on this

Frequently asked questions

What is Spring Security filter chain and authorization rules?

Spring Security is a chain of servlet filters in front of your controllers. Each request is authenticated (who are you?) and then authorized (are you allowed?) according to rules you define in a SecurityFilterChain bean.

What are the most common mistakes with Spring Security filter chain and authorization rules?

Wrong rule order exposing endpoints. Relying only on URL rules without ownership checks. Disabling CSRF on cookie-based apps. Custom filter at the wrong position in the chain.

How can I see Spring Security filter chain and authorization rules in real code?

Paste your own Java into Unravel and it will point out where spring security filter chain and authorization rules appears, explain how it works at the detail level you choose, and draw the flow of the code around it.