Spring Security config builder

Pick what the application needs and get a filter chain written against the current API. Spring Security 6 removed WebSecurityConfigurerAdapter and the chained DSL, so most examples still online neither compile nor mean what they did.

Authentication
CSRF
Other
Unmatched requests
Rules — first match wins
SecurityConfig.java

What changed in Spring Security 6

Spring Security 5Spring Security 6
extends WebSecurityConfigurerAdapterA SecurityFilterChain bean
authorizeRequests()authorizeHttpRequests()
antMatchers()requestMatchers()
.and() chainingLambda per configurer
csrf().disable()csrf(AbstractHttpConfigurer::disable)

The adapter class was removed outright, so a configuration extending it does not compile at all. The rest were deprecated first and removed in 6.1, which is why an example that worked last year may now fail on a patch upgrade.

Rule order decides everything

Rules are evaluated top to bottom and the first match wins. A broad rule above a narrow one makes the narrow one unreachable:

.requestMatchers("/api/**").permitAll()        // matches first
.requestMatchers("/api/admin/**").hasRole("ADMIN")  // never consulted

Nothing warns you about this at startup — the configuration is valid, the admin endpoint is simply public. The builder above flags it.

hasRole adds the prefix for you.hasRole("ADMIN") checks for the authority ROLE_ADMIN. WritinghasRole("ROLE_ADMIN") checks for ROLE_ROLE_ADMIN, which no one has, so the rule silently denies everyone. Use hasAuthority when you mean the raw string.

When disabling CSRF is fine, and when it is not

CSRF protection exists because a browser attaches cookies to requests another site triggers. It is needed exactly when credentials travel automatically:

  • Session cookie login — keep it on. Turning it off to make a form work is trading a real vulnerability for five minutes of debugging.
  • Bearer token API — turn it off. The browser never attaches the token by itself, so there is nothing to protect and every write would fail.
  • SPA with a session — use the cookie repository, which hands the token to JavaScript so the frontend can send it back.

Stateless means stateless

SessionCreationPolicy.STATELESS with form or OAuth2 login authenticates the user for exactly one request. There is nowhere to remember the login, so the next request starts over. It belongs with token authentication, where each request carries its own credentials.