javaspring-securityswaggeropenapispring-boot-3

Spring Boot 3 - Configure Spring Security to allow Swagger UI


I have built a REST API with Spring Boot 2 where I configured Swagger and implemented security using Spring Security. The objective is to secure all the requests to the API and allow access to the Swagger UI. Everything was working well on Spring Boot 2, but since I migrated to Spring Boot 3 every request has been secured, and I can no longer access the Swagger UI without authentication. Has anyone struggled with the same issue?

I'm using the following dependencies:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.4</version>
    <relativePath/>
</parent>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>

And the following configuration class:

@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(CsrfConfigurer::disable)
            .authorizeHttpRequests((authorize) -> authorize
                // Allow access to Swagger
                .requestMatchers(
                    "/v3/api-docs/**",
                    "/swagger-ui/**",
                    "/swagger-ui.html"
                ).permitAll()
                // Authenticate all other requests
                .anyRequest().authenticated()
            )
            // Use basic authentication (user/pass)
            .httpBasic(Customizer.withDefaults());

        return http.build();
    }

}

Solution

  • According to Migration Guide

    In 6.0, @Configuration is removed from @EnableWebSecurity, @EnableMethodSecurity, @EnableGlobalMethodSecurity, and @EnableGlobalAuthentication.

    To prepare for this, wherever you are using one of these annotations, you may need to add @Configuration.

    Just based on above information, you just should add one more annotation on SecurityConfiguration

    FROM :

    @EnableWebSecurity
    public class SecurityConfiguration {
    ...
    }
    

    TO:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration {
    
        ...
        }
    

    All is going to work great.