如何在Springfox Swagger提供的Swagger/v2/api-docs中启用CORS头?

Adr*_*ith 6 spring spring-mvc spring-boot springfox

我的项目中有以下文件:

@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class SwaggerConfig {

    @Bean
    public Docket apiSwagger2Documentation() { .... }
}
Run Code Online (Sandbox Code Playgroud)

在Application.java中有:

@SpringBootApplication
@ComponentScan(basePackages = { ... })
@EnableSwagger2
public class Application {
    ...
}
Run Code Online (Sandbox Code Playgroud)

Swagger JSON可用/v2/api-docs,工作正常.

我想做的是为该端点启用CORS头.

对于我自己的控制器,我已经添加@CrossOrigin到控制器类,那些API然后有CORS头,工作正常.但是对于Swagger JSON URL我自己没有编写控制器,所以我不能使用那个注释.

我已经添加了以下方法SwaggerConfig,如Spring FrameworkCORS支持中的 "全局CORS配置"中所述.

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        System.out.println("*** corsConfigurer called");
        return new WebMvcConfigurerAdapter() {
            @Override public void addCorsMappings(CorsRegistry registry) {
                System.out.println("*** addCorsMappings called");
                registry.addMapping("/v2/api-docs");
            }
        };
    }
Run Code Online (Sandbox Code Playgroud)

打印两个打印语句,因此调用该方法.但是当我用curl调用URL时:

curl -H "Origin: foo.com"  \
   -H "Access-Control-Request-Method: GET"   \
   -X OPTIONS \ 
   --verbose  \
   http://localhost:9274/v2/api-docs
Run Code Online (Sandbox Code Playgroud)

CORS标头不在响应中.(与我自己的控制器方法相反,注释时@CrossOrigin,响应确实有CORS头.)

我使用的是springfox-swagger2版本2.7.0和spring-boot-starter-web 1.5.2.

如何在Swagger JSON API端点上启用CORS头?

Str*_*lok 11

我认为你需要一个通用的Web过滤器而不是Web Mvc配置.

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

    // Allow anyone and anything access. Probably ok for Swagger spec
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");

    source.registerCorsConfiguration("/v2/api-docs", config);
    return new CorsFilter(source);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这是一种享受:)昨天花了整个下午的时间。谢谢!我最后使用了 new CorsConfiguration().applyPermitDefaultValues() 。 (3认同)