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


92

我的项目有Spring Security。主要问题:无法访问http:// localhost:8080 / api / v2 / api-docs上的大写URL 。它说缺少或无效的授权标头。

浏览器窗口的屏幕快照 我的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>

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;
}

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/");
}

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>

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

Answers:


176

将其添加到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/**");
    }

}

11
如果使用swagger-ui,则需要这样的内容:.antMatchers(“ / v2 / api-docs”,“ / configuration / ui”,“ / swagger-resources”,“ / configuration / security”,“ / swagger-ui html的”, “/ webjars / **”, “/招摇资源/配置/ UI”, “/招摇-ui.html”)permitAll()。
丹尼尔马丁

2
就我而言,此规则有效:.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()
nikolai.serdiuk

6
需要更多规则:.antMatchers(“ /”,“ / csrf”,“ / v2 / api-docs”,“ / swagger-resources / configuration / ui”,“ / configuration / ui”,“ / swagger-resources”, “ / swagger-resources / configuration / security”,“ / configuration / security”,“ / swagger-ui.html”,“ / webjars / **”)。permitAll()
MateŠimović18年

5
谢谢你的回答!是否存在允许访问webjars / **的安全风险?
ssimm '18

非常有用的答案
Praveenkumar Beedanal

26

我使用/ 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/**");

}

完善!解决了问题。
马杜

24

我在使用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
    }

}

2
添加{ "timestamp": 1519798917075, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/<some path>/shop" }
完此类

@ChandrakantAudhutwar deleteantMatchers("/**").authenticated()语句或替换为您自己的身份验证配置。小心,您最好了解安全性。
naXa

是的,它有效。我当时只想绕过swagger-ui,但要绕过其他API,因为它很安全。现在我的API也被绕过了。
Chandrakant Audhutwar

@ChandrakantAudhutwar,您不需要将整个SecurityConfiguration类都复制粘贴到您的项目中。您应该拥有自己的SecurityConfiguration地方,允许请求Swagger UI资源并保持API安全。
naXa

AuthorizationServerConfigurerAdapter实现了使API进行身份验证的类。
Chandrakant Audhutwar

12

对于那些使用较新的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/**");
    }
}

1
注意:如果这阻止您收到“需要身份验证”错误,而只是显示空白页,则我还必须在该列表中添加“ / swagger-resources / **”和“ / swagger-resources”,并进行了修复对我来说。
维尼修斯中号

5

如果您的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();
}

duliu1990是正确的,自springfox 2.5+起,所有springfox资源(包括swagger)都移到了/swagger-resources/v2/api-docs是默认的swagger api端点(与UI无关),可以使用配置变量springfox.documentation.swagger.v2.path springfox
Mahieddine M. Ichir,

3

此页面或多或少都有答案,但并非都在一个地方。我当时正在处理同一问题,并在此问题上花费了很多时间。现在我有了更好的理解,我想在这里分享:

我使用Spring Websecurity启用Swagger ui:

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

您可能需要告诉Spring Websecurity忽略几种摇摆路径模式的身份验证。我正在使用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", "/");
}
}

II使用拦截器启用swagger ui

通常,您可能不想截获swagger-ui.html发出的请求。下面排除代码的几种波动模式:

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

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

}

由于您可能必须启用@EnableWebMvc来添加拦截器,所以您可能还必须添加资源处理程序以像我在上述代码片段中所做的那样大张旗鼓。


为什么要添加/csrf排除项?
维沙尔

2

仅限于Swagger相关资源:

.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");

2

这是带有Spring Security的Swagger的完整解决方案。我们可能只想在开发和QA环境中启用Swagger,而在生产环境中禁用它。因此,我prop.swagger.enabled仅在开发/质量保证环境中使用属性()作为标志来绕过swagger-ui的spring安全认证。

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

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

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

1

我正在使用Spring Boot5。我有这个控制器,我希望未经身份验证的用户调用它。

  //Builds a form to send to devices   
@RequestMapping(value = "/{id}/ViewFormit", method = RequestMethod.GET)
@ResponseBody
String doFormIT(@PathVariable String id) {
    try
    {
        //Get a list of forms applicable to the current user
        FormService parent = new FormService();

这是我在配置中所做的。

  @Override
   protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers(
                    "/registration**",
                    "/{^[\\\\d]$}/ViewFormit",

希望这可以帮助....


0

考虑到所有使用url模式定位的API请求,/api/..您可以使用以下配置告诉spring仅保护此url模式。这意味着您要告诉spring保护什么而不是忽略什么。

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
     .authorizeRequests()
      .antMatchers("/api/**").authenticated()
      .anyRequest().permitAll()
      .and()
    .httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

1
感谢您提供此代码段,这可能会提供一些有限的短期帮助。通过说明为什么这是一个很好的解决方案,正确的解释将大大提高其长期价值,并且对于其他存在类似问题的读者来说,它将变得更加有用。请编辑您的答案以添加一些解释,包括您所做的假设。
Toby Speight,
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.