Spring Security 6 ignore security configuration from dependency

1.1k Views Asked by At

I am migrating from Spring Security 5.7.x to 6.1.0. After fixing all the javax -> jakarta and remove WebSecurityConfigurerAdapter and added the security configuration from the dependency. And now it seems like my main project is ignoring the security configuration from dependency.

The security configuration from the dependency.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@Slf4j
public class WebSecurityConfig {

    final private AuthFilter authFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .formLogin(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(sessionManager -> sessionManager.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(exceptionHandling -> exceptionHandling.authenticationEntryPoint(
                        (request, response, ex) -> {
                    log.error("Unauthorized request - {}", ex.getMessage());
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
                }))
                .authorizeHttpRequests(
                        authorizeHttpRequest -> authorizeHttpRequest
                                .requestMatchers("/**").permitAll()
                                .anyRequest().authenticated())
                .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
                .httpBasic(Customizer.withDefaults())
                .build();
    }

AuthFilter

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthFilter extends OncePerRequestFilter {}

I'm expecting the AuthFilter will be called first but it didn't even run to it. Seems like it's ignored.

Anyone has any ideas which lead to this? Let me know which part of the configuration you wanted to take a look.

2

There are 2 best solutions below

0
On

Can you please add WebSecurityConfig in org.springframework.boot.autoconfigure.AutoConfiguration.imports file which is defined under the resources directory shown in image.

directory structure

1
On

The problem might be related to your custom bean name filterChain being the same as some other coming from the context. Could you try renaming it?

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@Slf4j
public class WebSecurityConfig {

    final private AuthFilter authFilter;

    @Bean
    public SecurityFilterChain myCustomFilterChain(HttpSecurity http) throws Exception {