为集成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
antMatchersincludes 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
- Start your Spring Boot application.
- 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. - Enter the credentials you defined (
swagger-admin/SecurePass123!by default) to access the Swagger UI. - Test any other API endpoint—they should load without requiring authentication.
内容的提问来源于stack exchange,提问作者Cortlendt
相关产品推荐
相关产品推荐

