【问题标题】:Allow anonymous access to springdoc-openapi-ui with Spring Security允许使用 Spring Security 匿名访问 springdoc-openapi-ui
【发布时间】:2020-05-10 21:30:58
【问题描述】:

如何在受 Spring Security 保护的 Spring Boot 应用程序中允许匿名访问 springdoc-openapi-ui (OpenAPI 3.0 /swagger-ui.html)?

【问题讨论】:

    标签: java spring spring-security openapi springdoc


    【解决方案1】:

    要使用 springdoc-openapi-ui /swagger-ui.html,请使用 permitAll 方法允许匿名访问 WebSecurityConfigurerAdapter 中的以下端点:

    • /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()
      }
    }
    

    确保项目具有以下依赖项:

    【讨论】:

    【解决方案2】:

    除了 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

    【讨论】:

      【解决方案3】:

      要在 spring webflux 中获取访问权限,您必须执行以下操作,并使用 spring-doc 版本 1.5.2 进行测试:

      swagger 网页在路径为 /webjars/swagger-ui 的 html 资源上失败。

      @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();
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-10-09
        • 2014-09-02
        • 2021-06-03
        • 2018-12-10
        • 2021-01-04
        • 2020-11-11
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多