Spring Boot 3配置Spring Security后无法访问Swagger UI求助
问题描述
我用Spring Boot 2构建了REST API,配置了Swagger并通过Spring Security实现安全控制,目标是保护所有API请求但允许访问Swagger UI。在Spring Boot 2下一切正常,但迁移到Spring Boot 3后,所有请求都被拦截,未认证无法访问Swagger UI。
使用的依赖
<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>
现有配置类
@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(); } }
解决方案
这个问题源于Spring Boot 3搭配的Spring Security 6对请求匹配规则更严格,同时springdoc-openapi-starter-webmvc-ui的前端资源依赖webjars路径,需要显式放行才能正常加载Swagger UI。
修正后的Security配置需添加/webjars/swagger-ui/**路径到允许列表,另外/swagger-ui.html在Spring Boot 3版本的springdoc中已不再使用,实际入口是/swagger-ui/index.html,不过/swagger-ui/**已包含该路径,可保留但非必需。
修正后的代码如下:
@EnableWebSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(CsrfConfigurer::disable) .authorizeHttpRequests(authorize -> authorize // 放行Swagger相关所有路径 .requestMatchers( "/v3/api-docs/**", "/swagger-ui/**", "/webjars/swagger-ui/**" ).permitAll() // 其他请求必须认证 .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()); return http.build(); } }
关键说明
/webjars/swagger-ui/**:springdoc-ui的前端静态资源(如CSS、JS文件)存放在该路径下,Spring Security 6不会自动放行,必须显式配置。/v3/api-docs/**:OpenAPI接口文档数据路径,Swagger UI需拉取该数据渲染页面。/swagger-ui/**:包含Swagger UI的入口页面及相关路由。
内容的提问来源于stack exchange,提问作者João Carreira
相关产品推荐
相关产品推荐

