Updating to Spring Security 6.0 – replacing Removed and Deprecated functionality for securing requests

In Spring Security 6.0,
antMatchers() as well as other configuration methods for securing requests
(namely mvcMatchers() and regexMatchers()) have been removed from the API.

An overloaded method requestMatchers() was introduced as a uniform mean for securing requests. The flavors of requestMatchers() facilitate all the ways of restricting requests that were supported by the removed methods.

Also, method authorizeRequests() has been deprecated and shouldn’t be used anymore. A recommended replacement – authorizeHttpRequests() (you can find more information regarding these changes here).

That’s how your SecurityFilterChain might be defined in Spring Security 6.0:

public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
    return httpSecurity
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/token/**").permitAll()
            .anyRequest().authenticated()
        )
        .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
        .httpBasic(Customizer.withDefaults())
        .build();
}

Regarding deprecated annotation @EnableGlobalMethodSecurity it was replaced with @EnableMethodSecurity. The rationale behind this change is that with @EnableMethodSecurity property prePostEnabled needed to enable use of @PreAuthorize/@PostAuthorize and @PreFilter/@PostFilter is by default set to true.

So you no longer need to write prePostEnabled = true, just annotating your configuration class with @EnableMethodSecurity would be enough.

Leave a Comment