使用Java Config的全局CORS配置不起作用 [英] Global CORS configuration using Java Config is not working

查看:384
本文介绍了使用Java Config的全局CORS配置不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用Java配置来运行Global CORS配置。我不确定这是否是一个已知问题,因为其他人也有同样的问题:
Spring Global CORS配置不起作用但控制器级配置确实如此

I am having a hard-time to get Global CORS configuration using Java config to work. I'm not sure if it is a known issue because other people also have the same problem: Spring Global CORS configuration not working but Controller level config does

无论如何,让我进一步详细说明我要做的事情:

Anyway, let me elaborate further what I am trying to do:

我正在使用Spring 4.2.3.RELEASE(没有弹簧启动)。我正在尝试使用Java配置配置全局CORS配置,以便我可以使用属性文件中的@Value注入CORS域(allowed-Origin)。因为据我所知,我不能在mvc xml名称空间中为allowed-origin注入值,如下图所示(如果您知道任何其他解决此问题的方法,请通知我):

I'm using Spring 4.2.3.RELEASE (no spring boot). I am trying to configure Global CORS configuration using Java config so that I can inject the CORS domain (allowed-Origin) using @Value from the property file. Because to my knowledge, I cannot inject the value in mvc xml namespace for the allowed-origin as illustrated bellow (please let me know if you know any other approach to this problem):

<mvc:cors>
        <mvc:mapping path="/**" allowed-origins="${vrm.cors.domain}"
                     allowed-methods="*"
                     allowed-headers="*"
                     allow-credentials="false" max-age="3600"/>
</mvc:cors>

来自Spring参考文档这里,我试图使用java配置来配置Global CORS来解决问题。但是,我无法让CORS工作。代码在应用程序启动期间调用,但客户端的调用始终返回

From Spring reference document here, I am trying to configure Global CORS using java config to solve the problem. However, I cannot get CORS to work. The codes does call during application startup but call from the clients always return


没有'Access-Control-Allow-Origin'标题出现在请求的
资源。因此不允许来源' http:// localhost:3000 '
access

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access



@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Value("${vrm.cors.domain}")
    //vrm.cors.domain=/**
    private String corsDomain;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").
        .allowedOrigins(vrm.cors.domain);
    }
}


推荐答案

根据回答这个问题 https://stackoverflow.com/a/33823253

你可以像这样启用cors:

You can enable cors like this:

@EnableWebSecurity
@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {

  private final AppProperties appProperties;

  @Autowired
  public SecurityConfig(AppProperties appProperties) {
    this.appProperties = appProperties;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterBefore(corsFilter(), SessionManagementFilter.class) //adds your custom CorsFilter
        .authorizeRequests()
        .antMatchers("/**")
        .permitAll()
        .and()
        .csrf()
        .disable();
  }

  private CorsFilter corsFilter() {
    return new CorsFilterAdapter(
        appProperties.getClientUrls(),
        appProperties.getHeaders(),
        appProperties.getMethods())
        .corsFilter();
  }
}

其中 CrosFilterAdapter 是这样的:

public class CorsFilterAdapter {

  private final String[] clientUrls;
  private final String[] headers;
  private final String[] methods;

  public CorsFilterAdapter(String clientUrls, String headers, String methods) {
    this.clientUrls = clientUrls.split(",");
    this.headers = headers.split(",");
    this.methods = methods.split(",");
  }

  public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(false);
    for (String clientUrl : clientUrls) {
      config.addAllowedOrigin(clientUrl);
    }
    for (String header: headers) {
      config.addAllowedHeader(header);
    }
    for (String method : methods) {
      config.addAllowedMethod(method);
    }
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
  }
}

这篇关于使用Java Config的全局CORS配置不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆