Video in progress
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. authorizeHttpRequestschecks every dispatch, forward and error dispatches included. As a result the/errorpage is protected too, and when an error occurs you may see 401/403 instead of 500. You'll need to make/errorpermitAll().AuthenticationManageris no longer set up throughconfigure(AuthenticationManagerBuilder): if you declareUserDetailsServiceandPasswordEncoderbeans, Boot assembles it for you.@EnableMethodSecurity:prePostEnabledis 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/usersas 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.
Sign up to mark studied questions and save your progress.