You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为集成Springfox的Spring Boot应用添加Swagger Basic认证

Adding BASIC Authentication to Swagger in Spring Boot with Springfox

Here's a complete, production-ready implementation to secure your Swagger UI and related endpoints with BASIC authentication, while keeping all other API requests publicly accessible:

Step 1: Full Security Configuration Class

Your existing SecurityConfig is off to a great start—let's expand it to cover all Swagger endpoints and add proper user authentication setup:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                // Secure every Swagger-related endpoint
                .antMatchers(
                    "/swagger-ui/**",
                    "/swagger-resources/**",
                    "/v2/api-docs",
                    "/api/v1/swagger.json",
                    "/webjars/**"
                ).hasAuthority("SWAGGER")
                // Allow all other API requests without authentication
                .anyRequest().permitAll()
            .and()
                // Enable browser-native BASIC authentication prompt
                .httpBasic()
            .and()
                // Disable CSRF (safe for API-only apps using BASIC auth)
                .csrf().disable();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        // Create an in-memory user with access to Swagger
        UserDetails swaggerUser = User.withUsername("swagger-admin")
            .password(passwordEncoder().encode("SecurePass123!"))
            .authorities("SWAGGER")
            .build();

        return new InMemoryUserDetailsManager(swaggerUser);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // Use BCrypt for secure password hashing (never store plain text!)
        return new BCryptPasswordEncoder();
    }
}

Key Details Breakdown:

  • Comprehensive Swagger Endpoint Coverage: The antMatchers includes all paths used by Swagger UI, documentation files, and static resources to ensure the entire Swagger interface is protected.
  • BASIC Authentication: Enabled via .httpBasic() which triggers the browser's built-in login prompt when accessing Swagger routes.
  • Public API Access: .anyRequest().permitAll() ensures all non-Swagger endpoints remain accessible without authentication.
  • Secure User Setup: We use an in-memory user with a hashed password (via BCrypt) for simplicity—you can replace this with a database-backed user service for production.
  • CSRF Disabled: Safe for API-focused apps using BASIC auth, as CSRF is primarily a concern for form-based web apps.

Step 2: Confirm Required Dependencies

Ensure these dependencies are present in your project:

Maven (pom.xml):

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

<!-- Springfox Swagger 2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- Springfox Swagger UI -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Gradle (build.gradle):

// Spring Security
implementation 'org.springframework.boot:spring-boot-starter-security'

// Springfox Swagger 2
implementation 'io.springfox:springfox-swagger2:2.9.2'

// Springfox Swagger UI
implementation 'io.springfox:springfox-swagger-ui:2.9.2'

Testing the Implementation

  1. Start your Spring Boot application.
  2. Navigate to http://localhost:8080/swagger-ui.html (adjust port if your app uses a different one). You’ll see a BASIC auth login prompt.
  3. Enter the credentials you defined (swagger-admin / SecurePass123! by default) to access the Swagger UI.
  4. Test any other API endpoint—they should load without requiring authentication.

内容的提问来源于stack exchange,提问作者Cortlendt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:25:47