Video in progress

Strong Middle 🌱 Spring

What changed in the configuration when moving from Spring Security 5 to 6?

WebSecurityConfigurerAdapter was removed, so you now write SecurityFilterChain beans; authorizeHttpRequests instead of authorizeRequests, requestMatchers instead of antMatchers; @EnableMethodSecurity instead of @EnableGlobalMethodSecurity; jakarta instead of javax.

📖 Answer

The old code:

@Configuration
class Old extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")
            .and().formLogin();
    }
}

The new one:

@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(a -> a
            .requestMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated())
        .formLogin(Customizer.withDefaults());
    return http.build();
}

These usually catch people in a migration:

  • Lambda DSL. The .and() chain is deprecated and will be removed in version 7, so every section goes inside a lambda.
  • authorizeHttpRequests checks every dispatch, forward and error dispatches included. As a result the /error page is protected too, and when an error occurs you may see 401/403 instead of 500. You'll need to make /error permitAll().
  • AuthenticationManager is no longer set up through configure(AuthenticationManagerBuilder): if you declare UserDetailsService and PasswordEncoder beans, Boot assembles it for you.
  • @EnableMethodSecurity: prePostEnabled is on by default.
  • SecurityContext persistence. In 6 the context isn't saved to the session automatically; if you log the user in yourself (a custom filter), you have to call SecurityContextRepository.saveContext.
  • Trailing slash. Spring 6 MVC no longer treats /users/ and /users as the same: clients calling /users/ get a 404. This is good for security: in Spring 5, antMatchers("/users") didn't catch /users/, yet the controller accepted it, so the rule could be bypassed.

If there are no tests for permissions after the migration (@WithMockUser, @WithAnonymousUser), don't make these changes blindly.