1、在使用springBoot+springSecurity整合Swagger2的过程中,swagger每次打开都会弹出登录框,然后我并不想让它弹出,如果关闭登录弹框
2、如果修改swagger访问路径
关闭 Spring Security 中的登录弹窗:
如果你不想在访问 Swagger 文档时弹出登录框,可以在 Spring Security 配置类中配置一个新的 HttpSecurity 配置对 Swagger 的路径进行特殊处理。
首先在 Spring Security 配置类中配置所有路径都需要进行身份认证
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
//...
}
然后,针对 Swagger 的路径进行特殊处理,在配置中添加
.antMatchers("/swagger-ui.html").permitAll() .antMatchers("/swagger-resources/").permitAll() .antMatchers("/v2/api-docs").permitAll() .antMatchers("/webjars/").permitAll()
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/v2/api-docs").permitAll()
.antMatchers("/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
//...
}
修改swagger访问路径
你可以使用 .pathProvider(new RelativePathProvider(servletContext)) 修改 swagger 访问路径
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.pathProvider(new RelativePathProvider(servletContext))
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
}
或者 .useDefaultResponseMessages(false) 来隐藏swagger的默认访问路径
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
}
或者在 application.properties 或者 application.yml 文件中配置默认路径
swagger.path=/yourpath
注意: 上述所有路径设置都可以根据需要调整,来满足你的需求。