Spring Security放行Swagger路径后,Swagger UI仍要求登录凭证
问题分析
你已在Spring Boot 3.3.5项目中集成Swagger,/v3/api-docs可正常访问,但/swagger-ui/index.html#/始终弹出登录凭证输入框,尽管已在Spring Security中配置了Swagger相关路径的放行规则。
解决方案
1. 调整Spring Security规则顺序与路径覆盖
Spring Security的请求匹配器按顺序执行,需将Swagger路径的放行规则优先放在所有认证规则之前,确保优先匹配。同时补充/springdoc/**路径(springdoc-openapi内部可能用到该路径),避免遗漏:
修改后的WebAuthorizationConfig代码:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; import static com.francislainy.sobe.enums.UserRole.ADMIN; import static com.francislainy.sobe.enums.UserRole.USER; @Configuration public class WebAuthorizationConfig { @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .cors(Customizer.withDefaults()) .csrf(c -> c.disable()) .authorizeHttpRequests(c -> c // 优先放行所有Swagger相关路径 .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**", "/webjars/**", "/springdoc/**").permitAll() .requestMatchers(HttpMethod.POST, "/api/v1/auth/*").permitAll() // 后续配置需要认证的接口 .requestMatchers(HttpMethod.POST, "/api/v1/test-admin").hasRole(String.valueOf(ADMIN)) .requestMatchers(HttpMethod.GET, "/api/v1/test-user").hasRole(String.valueOf(USER)) .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()); return http.build(); } }
2. 排除浏览器缓存干扰
使用浏览器无痕模式访问Swagger UI,或清除浏览器的认证缓存(可通过开发者工具的Application标签下清除存储数据),避免旧的认证会话残留导致弹窗。
3. 检查是否存在多SecurityFilterChain冲突
确认项目中仅存在一个SecurityFilterChain配置类,若有多个配置类,可能导致规则覆盖或冲突,需合并为单一配置。
4. 开启调试日志排查匹配规则
在application.yml中添加Spring Security调试日志,查看请求的匹配过程,确认Swagger路径是否被正确放行:
logging: level: org.springframework.security: DEBUG
访问Swagger UI后,查看日志中类似如下的匹配记录,确认请求是否命中了permitAll规则:
Checking match of request : '/swagger-ui/index.html'; against '/swagger-ui/**' Authorized permitAll
5. 版本兼容性确认
你当前使用的springdoc-openapi-starter-webmvc-ui 2.6.0与Spring Boot 3.3.5兼容,若问题依旧,可尝试升级到最新兼容版本(如2.7.0)。
补充说明
你使用的swagger-parser和snakeyaml依赖是通过openapi.yml配置Swagger的必要依赖,不会导致Spring Security拦截问题,无需移除。
内容的提问来源于stack exchange,提问作者Francislainy Campos

