Configuring Spring Security to Allow Swagger URL Access Without Authentication

Nov 22, 2025 · Programming · 7 views · 7.8

Keywords: Spring Security | Swagger | Springfox | Authentication Configuration | Whitelist

Abstract: This article provides a comprehensive analysis of Swagger UI access issues in Spring Security environments, offering complete solutions through WebSecurity configuration whitelists, including compatibility handling for Springfox 2.x and 3.x versions, with in-depth exploration of Spring Security filter chain mechanisms and permission control principles.

Problem Background and Root Cause Analysis

When integrating Spring Security into Spring Boot projects, developers often encounter issues accessing Swagger UI documentation. According to the provided Q&A data, users using Springfox 2.4.0 version experience "Missing or invalid Authorization header" errors when accessing http://localhost:8080/api/v2/api-docs. The fundamental cause of this problem lies in Spring Security's default configuration requiring authentication for all requests.

From the security configuration code, we can see that in the WebSecurityConfiguration class, the authorizeRequests() method configures .antMatchers("/api/**").authenticated() and .anyRequest().authenticated(), meaning all paths starting with /api and any other requests require authentication. Since Swagger-related resource paths (such as /v2/api-docs, /swagger-ui.html, etc.) fall within these path ranges, they are intercepted by Spring Security.

Core Solution: WebSecurity Whitelist Configuration

The optimal solution involves configuring resource whitelists by overriding the configure(WebSecurity web) method. This approach fundamentally differs from the configure(HttpSecurity http) method:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = { "com.musigma.esp2.service", "com.musigma.esp2.security" })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
                                   "/configuration/ui",
                                   "/swagger-resources/**",
                                   "/configuration/security",
                                   "/swagger-ui.html",
                                   "/webjars/**");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(this.unauthorizedHandler)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .authorizeRequests()
            .antMatchers("/auth/login", "/auth/logout").permitAll()
            .antMatchers("/api/**").authenticated()
            .anyRequest().authenticated();

        httpSecurity.addFilterBefore(loginFilter(), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.addFilterBefore(new StatelessTokenAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
    }
}

Resources configured using web.ignoring() in the configure(WebSecurity web) method completely bypass Spring Security's entire filter chain, including authentication and authorization checks. This approach is more thorough than using permitAll() in configure(HttpSecurity http), because permitAll() still passes through security filters, only without requiring authentication.

Springfox Version Compatibility Handling

As Springfox versions evolve, Swagger UI resource paths have also changed. For Springfox 3.x versions, additional paths need to be included:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(
        // Springfox 2.x
        "/v2/api-docs",
        "/configuration/ui",
        "/swagger-resources/**",
        "/configuration/security",
        "/swagger-ui.html",
        "/webjars/**",
        // Springfox 3.x (OpenAPI)
        "/v3/api-docs/**",
        "/swagger-ui/**"
    );
}

This configuration approach ensures compatibility across different Springfox versions. The issue mentioned in the reference article also confirms this point – using .requestMatchers("/swagger-ui.html").permitAll() may still fail to provide access in certain scenarios, while using web.ignoring() completely resolves the problem.

Technical Principles Deep Dive

Understanding Spring Security's filter chain mechanism is crucial to comprehending this issue. When requests reach the application, they pass through multiple security filters sequentially:

  1. SecurityContextPersistenceFilter: Responsible for security context storage and restoration
  2. UsernamePasswordAuthenticationFilter: Handles form login authentication
  3. BasicAuthenticationFilter: Handles HTTP Basic authentication
  4. Authorization Filter: Performs authorization checks

Paths configured with web.ignoring() completely skip the entire security filter chain, while paths using permitAll(), although not requiring authentication, still pass through other parts of the filter chain. This explains why permitAll() may not completely solve the problem in complex security configurations.

Best Practices and Considerations

In actual project configurations, we recommend following these best practices:

1. Centralized Whitelist Management: Manage all publicly accessible paths centrally for easier maintenance:

private static final String[] AUTH_WHITELIST = {
    "/v2/api-docs",
    "/swagger-resources",
    "/swagger-resources/**",
    "/configuration/ui",
    "/configuration/security",
    "/swagger-ui.html",
    "/webjars/**",
    "/v3/api-docs/**",
    "/swagger-ui/**"
};

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(AUTH_WHITELIST);
}

2. Environment Differentiation: Consider disabling Swagger UI in production environments, enabling it only in development environments:

@Profile({"dev", "test"})
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(AUTH_WHITELIST);
}

3. Resource Handler Configuration: Ensure Spring MVC correctly configures Swagger UI static resource handlers, as in the original configuration:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

Conclusion

By properly configuring Spring Security's configure(WebSecurity web) method, Swagger UI access issues in secure environments can be effectively resolved. This approach works not only for Springfox 2.x but also maintains compatibility with Springfox 3.x versions, providing a comprehensive technical solution. Understanding Spring Security filter chain working principles helps developers make correct configuration decisions in more complex security scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.