如何配置Spring Security以允许无需身份验证即可访问Swagger URL

shu*_*har 65 spring-mvc swagger swagger-ui swagger-2.0 springfox

我的项目有Spring Security.主要问题:无法访问http:// localhost:8080/api/v2/api-docs中的 swagger URL .它表示缺少或无效的授权标头.

浏览器窗口的屏幕截图 My pom.xml包含以下条目

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

SwaggerConfig:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", "myeaddress@company.com", "License of API", "API license URL");
    return apiInfo;
}
Run Code Online (Sandbox Code Playgroud)

AppConfig的:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.musigma.esp2" })
@Import(SwaggerConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {

// ========= Overrides ===========

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LocaleChangeInterceptor());
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}
Run Code Online (Sandbox Code Playgroud)

web.xml条目:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        com.musigma.esp2.configuration.AppConfig
        com.musigma.esp2.configuration.WebSecurityConfiguration
        com.musigma.esp2.configuration.PersistenceConfig
        com.musigma.esp2.configuration.ACLConfig
        com.musigma.esp2.configuration.SwaggerConfig
    </param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

WebSecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = { "com.musigma.esp2.service", "com.musigma.esp2.security" })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(this.unauthorizedHandler)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .authorizeRequests()
            .antMatchers("/auth/login", "/auth/logout").permitAll()
            .antMatchers("/api/**").authenticated()
            .anyRequest().authenticated();

        // custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
        httpSecurity.addFilterBefore(loginFilter(), UsernamePasswordAuthenticationFilter.class);

        // custom Token based authentication based on the header previously given to the client
        httpSecurity.addFilterBefore(new StatelessTokenAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 120

将此添加到WebSecurityConfiguration类应该可以解决问题.

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
                                   "/configuration/ui",
                                   "/swagger-resources/**",
                                   "/configuration/security",
                                   "/swagger-ui.html",
                                   "/webjars/**");
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用招摇的用户界面,你需要像这样:.antMatchers( "/ V2/API-文档", "/配置/ UI", "/招摇资源", "/配置/安全","/招摇的UI .html","/ webjars/**","/ swagger-resources/configuration/ui","/ swagger-ui.html").permitAll() (9认同)
  • 需要更多规则:.antMatchers("/","/ csrf","/ v2/api-docs","/ swagger-resources/configuration/ui","/ configuration/ui","/ swagger-resources", "/ swagger-resources/configuration/security","/ configuration/security","/ swagger-ui.html","/ webjars/**").permitAll() (5认同)
  • 我必须将 `.., "/swagger-ui/**"...` 添加到该列表中 (5认同)
  • 感谢您的回答!是否存在允许访问webjars / **的安全风险? (3认同)
  • 在我的情况下,此规则正在起作用:.antMatchers("/ v2/api-docs","/ configuration/ui","/ swagger-resources","/ configuration/security","/ swagger-ui.html", "/ webjars/**","/ swagger-resources/configuration/ui","/ swagge r-ui.html","/ swagger-resources/configuration/security").permitAll() (2认同)
  • 您能否添加各个端点的描述以及为什么需要允许它们?我只允许 `/webjars/swagger-ui/**`、`swagger-ui.html` 和 `/v3/api-docs/**` ,到目前为止一切似乎都正常,但也许有一些 swagger 功能我忽略了?或者“配置”端点仅适用于 springfox? (2认同)

小智 19

我使用/ configuration/**和/ swagger-resources/**进行了更新,它对我有用.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");

}
Run Code Online (Sandbox Code Playgroud)


Den*_*lot 17

对于那些使用较新的 swagger 3 版本的人 org.springdoc:springdoc-openapi-ui

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:如果这阻止您收到“需要身份验证”错误,但只显示一个空白页面,我还必须在该列表中添加“/swagger-resources/**”和“/swagger-resources”并修复对我来说。 (3认同)

naX*_*aXa 15

我使用Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0时遇到了同样的问题.我使用以下安全配置解决了这个问题,该配置允许公共访问Swagger UI资源.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
            // other public endpoints of your API may be appended to this array
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                // ... here goes your custom security configuration
                authorizeRequests().
                antMatchers(AUTH_WHITELIST).permitAll().  // whitelist Swagger UI resources
                // ... here goes your custom security configuration
                antMatchers("/**").authenticated();  // require authentication for any endpoint that's not whitelisted
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 添加此类后,我可以看到 swagger-ui,但即使使用 access_token,也无法通过邮递员访问 API,出现如下访问禁止错误,`{ "timestamp": 1519798917075, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/&lt;some path&gt;/shop" }` (2认同)
  • 我知道这个答案已经过时了,但是如果您将“/swagger-ui/**”添加到列表中,那就完美了。Springfox 3.0.0 URL 是这样的。 (2认同)

小智 6

如果您的 springfox 版本高于 2.5?应该添加 WebSecurityConfiguration 如下:

@Override
public void configure(HttpSecurity http) throws Exception {
    // TODO Auto-generated method stub
    http.authorizeRequests()
        .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
        .and()
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .csrf().disable();
}
Run Code Online (Sandbox Code Playgroud)


Rup*_*mar 6

一些安全配置,你就可以向所有人开放了

对于斯瓦格 V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}
Run Code Online (Sandbox Code Playgroud)

适用于斯瓦格 V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/v3/api-docs",  
            "/swagger-resources/**", 
            "/swagger-ui/**",
             };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}
Run Code Online (Sandbox Code Playgroud)


Gre*_*reg 6

如果您使用 Spring Boot 3,则需要使用:正如文档简介springdoc-openapi-starter-webmvc-ui中所写

并使用安全配置,如下所示:

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
@RequiredArgsConstructor
public class SecurityConfiguration {

   @Bean
   public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
       return http
               .csrf().disable()
               .authorizeHttpRequests(a -> a
                       .requestMatchers("/v3/**", "/swagger-ui/**").permitAll()
                       .anyRequest().authenticated()
               ).build();
   }
}
Run Code Online (Sandbox Code Playgroud)
  • 招摇用户界面:http://{your host}:{your port}/swagger-ui/index.html
  • JSON:http://{your host}:{your port}/v3/api-docs
  • yaml:http://{your host}:{your port}/v3/api-docs.yaml


cha*_*evx 5

此页面或多或少有答案,但所有答案都不在一处。我正在处理同样的问题并花了相当多的时间。现在我有了更好的理解,我想在这里分享:

我使用 Spring websecurity 启用 Swagger ui:

如果您默认启用了 Spring Websecurity,它将阻止对应用程序的所有请求并返回 401。但是,为了在浏览器中加载 swagger-ui.html,需要多次调用来收集数据。最好的调试方法是在浏览器(如谷歌浏览器)中打开 swagger-ui.html 并使用开发人员选项(“F12”键)。您可以看到页面加载时进行的多个调用,如果 swagger-ui 未完全加载,则可能其中一些调用失败。

您可能需要告诉 Spring websecurity 忽略几种 swagger 路径模式的身份验证。我正在使用 swagger-ui 2.9.2,在我的例子中,下面是我必须忽略的模式:

但是,如果您使用不同的版本,您的版本可能会发生变化。正如我之前所说,您可能必须通过浏览器中的开发人员选项来找出您的。

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", 
            "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
            , "/webjars/**", "/csrf", "/");
}
}
Run Code Online (Sandbox Code Playgroud)

II 使用拦截器启用 swagger ui

通常,您可能不想拦截 swagger-ui.html 发出的请求。要排除以下几种 swagger 模式,代码如下:

大多数网络安全和拦截器的案例模式都是相同的。

@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {

@Autowired
RetrieveInterceptor validationInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {

    registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
    .excludePathPatterns("/v2/api-docs", "/configuration/ui", 
            "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
            , "/webjars/**", "/csrf", "/");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

}
Run Code Online (Sandbox Code Playgroud)

由于您可能必须启用 @EnableWebMvc 来添加拦截器,因此您可能还必须向 swagger 添加资源处理程序,类似于我在上面的代码片段中所做的操作。