允许使用spring security匿名访问springdoc openapi ui

yks3o0rb  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(729)

如何允许匿名访问springdoc openapi ui(openapi 3.0 /swagger-ui.html )在由spring security保护的spring引导应用程序中?

qv7cva1a

qv7cva1a1#

除了evgeniy的回答之外,我还添加了适当的配置,以避免与swagger的ui(如js、html、图像和其他文件)中使用的文档获取发生冲突,同样在securityconfig类中也会这样:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   //Other configuration methods

   @Override
   public void configure(WebSecurity web) {
    web.ignoring()
    .antMatchers("/v3/api-docs/**", "/swagger-ui/**");
   }
}

如果没有这个配置,即使ui看起来像是加载的,但是 401: Unauthorized 加载上述文件时,可能会在后台调用中出现。

nhaq1z21

nhaq1z212#

为了在SpringWebFlux中获得访问权限,您必须执行以下操作,并使用SpringDocVersion1.5.2进行了测试:
swagger网页在路径为的html资源上失败 /webjars/swagger-ui .

@Configuration
@EnableWebFluxSecurity
public class WebSecurityConfig {

  @Bean
  SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http.
        .authorizeExchange()
        .pathMatchers(
            "/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html", "/webjars/swagger-ui/**")
        .permitAll()
        .anyExchange()
        .authenticated()
        .and()
        .build();
  }
}
x6yk4ghg

x6yk4ghg3#

使用springdoc openapi ui /swagger-ui.html ,允许匿名访问 WebSecurityConfigurerAdapter 使用 permitAll 方法: /v3/api-docs/** /swagger-ui/**/swagger-ui.html 例子:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.
        .authorizeRequests()
        .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
        .anyRequest().authenticated()
        .and()
        .httpBasic(); //or anything else, e.g. .oauth2ResourceServer().jwt()
  }
}

确保项目具有以下依赖项:
组织。springdoc:springdoc-openapi-ui
组织。springdoc:springdoc-openapi-security

相关问题