迁移至Java 17后Swagger UI已配置忽略仍提示登录的问题
迁移至Java 17后Swagger UI仍提示登录的问题排查
问题描述
项目迁移到Java 17后,已在安全配置中忽略Swagger相关路径的登录校验,但Swagger UI仍弹出登录提示,需排查遗漏的配置项。
相关配置
Maven依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
Web Security配置
// Web Security Config public static final String[] excludedURLs = { "/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/**"}; @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().antMatchers(excludedURLs); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authenticationProvider(XXXXAPIAuthenticationProvider) .httpBasic() .and() .authorizeRequests() .antMatchers(excludedURLs).permitAll() .anyRequest().authenticated() .and() .addFilter(getXXXXXBasicAuthenticationFilter()) .addFilterBefore(getOktaAuthFilter(), XXXXXXBasicAuthenticationFilter.class) .csrf().disable(); return http.build(); }
Swagger配置
// Swagger Config @Profile({"Test","STAGE"}) @Configuration @EnableSwagger2 public class SwaggerConfig { private static final String AUTHORIZATION_HEADER = "Authorization"; public static final String DEFAULT_INCLUDE_PATTERN = "/.*"; @Bean public Docket api() { Docket docket=new Docket(DocumentationType.SWAGGER_2) .securityContexts(Lists.newArrayList(securityContext())) .securitySchemes(Lists.newArrayList(apiKey())) .useDefaultResponseMessages(false) .select() .apis(RequestHandlerSelectors .basePackage("com.XXXX.XXXX.controllers")) .paths(regex("/.*")) .build() .apiInfo(apiEndPointsInfo()); docket = docket.select() .paths(regex(DEFAULT_INCLUDE_PATTERN)) .build(); return docket; } }
已排查资源
已查阅以下内容:
- Why does springfox-swagger2 UI tell me "Unable to infer base url."
- springfox仓库的issue #2191、#2907
- Stack Overflow相关问题(编号56280202)
排查建议
- 版本兼容性问题:springfox 2.9.2未适配Java 17,Java 17移除了部分旧反射API,导致Swagger配置加载异常、路径匹配失效。建议升级springfox至3.x版本(如3.0.0),或添加JVM启动参数解除反射限制:
--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED。 - 补充Swagger路径:当前忽略的路径可能不完整,需添加
/swagger-ui/**(适配UI资源路径)和/v2/api-docs(明确API文档接口)到excludedURLs数组中。 - Spring路径匹配策略:若迁移时升级了Spring Boot至2.7+版本,默认路径匹配器为
PathPatternParser,但springfox 2.9.2依赖AntPathMatcher,需在配置文件中添加:spring.mvc.pathmatch.matching-strategy=ant_path_matcher。 - 安全配置冲突检查:确认自定义过滤器(
XXXXXBasicAuthenticationFilter、OktaAuthFilter)是否拦截了Swagger路径,可临时移除过滤器测试是否恢复正常。 - Swagger授权配置:当前SwaggerConfig中配置了
securityContexts和securitySchemes,会让UI默认显示授权输入框,若这不是预期的“登录提示”,可暂时注释这两行配置,确认是否是UI自带的授权提示而非系统登录校验。
内容的提问来源于stack exchange,提问作者SarangRN
相关产品推荐
相关产品推荐

