Skip to lesson

SecurityFilterChain configuration

Boot's default security fits a browser app with a login page. A REST API such as ShopLite needs its own rules: who may call what, how callers sign in, and which protections stay on. Where do you write them?

A @Configuration class with a SecurityFilterChain @Bean

A SecurityFilterChain is the object that holds one chain's request matcher and filters; you declare it as a bean. Your own chain replaces Boot's default chain completely.

Write the smallest useful SecurityConfig: one rule and one way to sign in. Then see in the lab what changes.

Example 1 · The smallest chain (security-lab)

Runs in: the security-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
package com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.web.SecurityFilterChain;
@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())            .httpBasic(Customizer.withDefaults());        return http.build();    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 401
Set-Cookie: JSESSIONID=BCF6C60C0F82256A21A389137A71CC49; Path=/; HttpOnly
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
...

$ curl -i -u asha:asha-pass-1 http://localhost:8080/api/v1/products/1
HTTP/1.1 200
...
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00}

$ curl -i -u admin:admin-pass-1 -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","price":999.00}' http://localhost:8080/api/v1/products
HTTP/1.1 401
...

$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/login
401

Security filter chains: 1
 1. DisableEncodeUrlFilter
 2. WebAsyncManagerIntegrationFilter
 3. SecurityContextHolderFilter
 4. HeaderWriterFilter
 5. CsrfFilter
 6. LogoutFilter
 7. BasicAuthenticationFilter
 8. RequestCacheAwareFilter
 9. SecurityContextHolderAwareRequestFilter
10. AnonymousAuthenticationFilter
11. ExceptionTranslationFilter
12. AuthorizationFilter

What this code does

  • http.build() turns the description into a SecurityFilterChain; Spring then uses it instead of Boot's default chain.
  • The login page filters are gone (12 filters instead of 16), so /login is now just a protected URL: 401.
  • CsrfFilter is still there, so the admin's POST still fails, and a JSESSIONID cookie is still set. Example 2 fixes both.

You create the chain in a @Bean method that takes HttpSecurity, a builder Spring gives you, describe the rules on it, and return http.build(). The class around it is a normal @Configuration class.

Why write your own? Boot's default chain fits a browser app: a login page, CSRF tokens, a session cookie. A REST API such as ShopLite needs different choices, and later public endpoints and roles. In the lab the login page is gone, but the POST still fails, because CSRF protection is still on.

The lambda DSL: authorizeHttpRequests, httpBasic, formLogin, csrf, sessionManagement

CSRF (cross-site request forgery) is an attack where another website makes the victim's browser send a request that carries the victim's cookie automatically. Spring Security blocks such writes unless they carry a token.

Configure sign-in, CSRF and sessions in the Spring Security 7 lambda style, one method per part, and compare the filters before and after.

Example 2 · httpBasic, csrf and sessionManagement together (security-lab)

Runs in: the security-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
package com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;
@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .anyRequest().authenticated())            .httpBasic(Customizer.withDefaults())            .csrf(csrf -> csrf.disable())                       // no cookies are used, so no CSRF risk (module 4)            .sessionManagement(session -> session                .sessionCreationPolicy(SessionCreationPolicy.STATELESS));   // no JSESSIONID, no server session        return http.build();    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 0
Date: Fri, 16 Oct 2026 05:38:57 GMT

$ curl -i -u admin:admin-pass-1 -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","price":999.00}' http://localhost:8080/api/v1/products
HTTP/1.1 201
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:38:59 GMT

{"id":10,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","price":999.00}

Security filter chains: 1
 1. DisableEncodeUrlFilter
 2. WebAsyncManagerIntegrationFilter
 3. SecurityContextHolderFilter
 4. HeaderWriterFilter
 5. LogoutFilter
 6. BasicAuthenticationFilter
 7. RequestCacheAwareFilter
 8. SecurityContextHolderAwareRequestFilter
 9. AnonymousAuthenticationFilter
10. SessionManagementFilter
11. ExceptionTranslationFilter
12. AuthorizationFilter

What this code does

  • The POST now works (201): CsrfFilter is gone from the list, and the password is checked by BasicAuthenticationFilter.
  • No Set-Cookie: JSESSIONID header any more: with STATELESS the server keeps nothing between requests, so every request must carry its credentials.
  • SessionManagementFilter appears because session management is configured; it enforces the stateless policy.

In the lambda DSL each part of the configuration is one method on http that takes a lambda (or Customizer.withDefaults() for the defaults). The main parts:

  • authorizeHttpRequests(auth -> ...): the access rules, checked by AuthorizationFilter.
  • httpBasic(Customizer.withDefaults()) and formLogin(Customizer.withDefaults()): the ways to sign in. Each one adds its filter; leave out what you do not use.
  • csrf(csrf -> csrf.disable()): CSRF protection, on unless you turn it off.
  • sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)): never create a server session or a JSESSIONID cookie.

ShopLite turns CSRF off with a reason written in the code. ShopLite never uses cookies for sign-in: the client must put credentials in the Authorization header on every call, which another website cannot do. The HTTP Basic and sessions module shows the attack, and when CSRF protection must stay on.

Disable CSRF only together with stateless sessions and header-based credentials. An app that signs users in with a session cookie must keep CSRF protection on.

anyRequest().authenticated() and what your own chain turns off

anyRequest().authenticated() is the final rule: every request that no earlier rule matched needs a signed-in user. It must be the last rule.

Run a chain that has a rule but no way to sign in, and see what a signed-in user gets.

Example 3 · A rule with no way to sign in: 403 for everyone (security-lab)

Runs in: the security-lab practice project (Spring Boot 4.1)

SecurityConfig.javaJava
package com.shoplite.lab.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.web.SecurityFilterChain;
@Configurationpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());   // no way to sign in        return http.build();    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 403
Set-Cookie: JSESSIONID=623456E6923EE5567EB715CC446FC043; Path=/; HttpOnly
...
Content-Length: 0

$ curl -i -u asha:asha-pass-1 http://localhost:8080/api/v1/products/1
HTTP/1.1 403
...
Content-Length: 0

Security filter chains: 1
 1. DisableEncodeUrlFilter
 2. WebAsyncManagerIntegrationFilter
 3. SecurityContextHolderFilter
 4. HeaderWriterFilter
 5. CsrfFilter
 6. LogoutFilter
 7. RequestCacheAwareFilter
 8. SecurityContextHolderAwareRequestFilter
 9. AnonymousAuthenticationFilter
10. ExceptionTranslationFilter
11. AuthorizationFilter

What this code does

  • No httpBasic and no formLogin, so there is no authentication filter in the list: the password in -u is never read.
  • With no sign-in method there is no entry point that could send 401, so Spring falls back to 403 for every caller.
  • Fix: add the sign-in method you want, such as httpBasic(Customizer.withDefaults()).

Leave anyRequest() out, and Spring Security 7 denies every request that no rule matched: safe but confusing; in the lab a signed-in asha got 403 for /api/v1/me. Defining your own SecurityFilterChain replaces Boot's whole default chain, not just one rule: you lose the form login and login page, and Boot's free pass for /actuator/health, which in shoplite-api now answers 401. The next lesson opens it again on purpose.

The classic mistake is a rule with no way to sign in. With only authorizeHttpRequests(...), there is no authentication filter and no entry point, so every caller gets 403, even with the right password.

Fix the error

Complete the chain

Read the real answer, then pick the line that fixes it.

Round 1 of 2

A signed-in user gets 403 for every request.

http
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.csrf(csrf -> csrf.disable());
return http.build();

Error

$ curl -i -u asha:asha-pass-1 http://localhost:8080/api/v1/products/1
HTTP/1.1 403

One place for all rules: com.shoplite.common.security

@EnableWebSecurity switches on Spring Security's web setup and creates the HttpSecurity builder. In a running web app Boot adds it for you.

Put every security rule of ShopLite in one class in com.shoplite.common.security, next to the other shared code.

Example 4 · src/main/java/com/shoplite/common/security/SecurityConfig.java

Runs in: the shoplite-api Spring Boot project

SecurityConfig.javaJava
package com.shoplite.common.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;
/** Every security rule of ShopLite lives in this one class. */@Configuration@EnableWebSecuritypublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        http            .authorizeHttpRequests(auth -> auth                .anyRequest().authenticated())            .httpBasic(Customizer.withDefaults())            // The API reads credentials from the Authorization header, never from a cookie,            // so a forged cross-site request cannot carry them: CSRF protection is not needed.            .csrf(csrf -> csrf.disable())            .sessionManagement(session -> session                .sessionCreationPolicy(SessionCreationPolicy.STATELESS));        return http.build();    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/1
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
...
Content-Length: 0

$ curl -i -u "dev:$SHOPLITE_DEV_PASSWORD" -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}' http://localhost:8080/api/v1/products
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:27:54 GMT

{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}

$ curl -i -u "dev:$SHOPLITE_DEV_PASSWORD" -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 204
...

$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/actuator/health
401
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/swagger-ui/index.html
401
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/login
401

What this code does

  • All of ShopLite's security rules are in this one class. The comment above csrf records why turning it off is safe here.
  • Writes work with the dev user (201 with Location, then 204), and there is no session cookie.
  • Health, Swagger UI and the catalogue now answer 401 too: your chain replaced Boot's defaults. The next lesson opens exactly what should be public.

SecurityConfig holds every access rule of the app in one bean, so a reviewer reads one file to know who may call what, and compares it with the access table in SECURITY.md. Scattered rules are easy to miss when a new endpoint arrives; one ordered list, read from top to bottom, is easy to review and to test. Later modules add more security classes to this package: the user lookup, the token service and the JSON error handlers.

In a running web app the app behaves the same without the annotation. But shoplite-api has an integration test that starts Spring with no web server (webEnvironment = NONE). Without @EnableWebSecurity that test fails with No qualifying bean of type '...HttpSecurity' available, because nothing creates the HttpSecurity builder outside a web app.

Startup failures from wrong configuration

BeanCreationException is the error Spring throws at startup when it cannot build a bean, such as securityFilterChain with a wrong rule.

Break the configuration in two ways and read the startup error. Then forget @Configuration and see that nothing fails at all.

Example 5 · Two startup failures and how to read them

Runs in: the shoplite-api Spring Boot project

Java
// Mistake 1: a specific rule after anyRequest().authorizeHttpRequests(auth -> auth    .anyRequest().authenticated()    .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll())   // line 20
// Mistake 2: ROLE_ written by hand in hasRole.authorizeHttpRequests(auth -> auth    .requestMatchers(HttpMethod.POST, "/api/v1/products/**").hasRole("ROLE_ADMIN")    .anyRequest().authenticated())
Sample output
Mistake 1 (shoplite-api):
... ERROR ... o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityFilterChain' defined in class path resource [com/shoplite/common/security/SecurityConfig.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'securityFilterChain' threw exception with message: Can't configure requestMatchers after anyRequest
...
Caused by: java.lang.IllegalStateException: Can't configure requestMatchers after anyRequest
	...
	at com.shoplite.common.security.SecurityConfig.lambda$securityFilterChain$0(SecurityConfig.java:20)
	...
	at com.shoplite.common.security.SecurityConfig.securityFilterChain(SecurityConfig.java:18)

Mistake 2 (security-lab):
Caused by: java.lang.IllegalArgumentException: ROLE_ADMIN should not start with ROLE_ since ROLE_ is automatically prepended when using hasAnyRole. Consider using hasAnyAuthority instead.

What this code does

  • The last Caused by gives the reason in plain words; SecurityConfig.java:20 points at the requestMatchers line that came after anyRequest().
  • Fix 1: move anyRequest() to the end. Fix 2: write hasRole("ADMIN"), or hasAuthority("ROLE_ADMIN").
  • Both fail at startup, before any request: the app never runs with broken rules.

Example 6 · Forgetting @Configuration: no error, wrong behaviour

Runs in: the shoplite-api Spring Boot project

SecurityConfig.javaJava
// @Configuration   <- forgottenpublic class SecurityConfig {
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {        ... same rules as Example 4 ...    }}
Sample output
$ curl -s -o /dev/null -w "%{http_code}\n" -u "dev:$SHOPLITE_DEV_PASSWORD" -H "Content-Type: application/json" -d '{"sku":"ACC-KB101","name":"Zebronics Keyboard","categoryId":4,"price":999.00,"stock":30}' http://localhost:8080/api/v1/products
401

$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/login
200

What this code does

  • Without @Configuration (or another stereotype) the class is not scanned, so its @Bean method never runs.
  • Boot's default chain is back: the POST fails with 401 again (CSRF) and the default login page answers 200.
  • When your rules seem ignored, look for the login page or the TRACE line Will secure any request with filters: ... DefaultLoginPageGeneratingFilter.

A startup failure is good news: the mistake is found on your laptop, not by an attacker. To read the error, skip the first long line and go to the last Caused by:; it says what is wrong. Then find the first at com.shoplite... line: it gives the file and line number in your config.

Two common ones: a requestMatchers(...) after anyRequest() ("Can't configure requestMatchers after anyRequest"), and hasRole("ROLE_ADMIN") ("should not start with ROLE_"), because hasRole adds the prefix itself. One mistake gives no error: forgetting @Configuration. The class is never read, Boot's default chain stays, and the login page is back. If your rules seem ignored, check the annotation first.

Find the bug

Find the configuration mistake

Click the line that breaks the configuration.

The app stops at startup with "role should not start with ROLE_".

Round 1 of 3

Next step

Check your understanding

12 quick questions