【问题标题】:Cross Origin Request Blocked: The Same Origin Policy disallows reading the remote resource(Access Control Allow Origin doens not match '(null)')跨域请求被阻止:同源策略不允许读取远程资源(访问控制允许来源不匹配'(null)')
【发布时间】:2017-05-03 10:24:53
【问题描述】:

Angular 2.0 应用程序正在尝试与 Rest Server 交互,遇到 CORS 问题

下面是我的 CORSFilter 实现

response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }

如果我在本地部署(客户端在 3000 端口上,服务器在 8080 上),令人惊讶的是相同的 war 文件,它工作正常,在本地我没有得到 access-control-allow-credentials 和 access-control-expose-headers,如果我们在服务器中部署它,就会得到这些标头并且 CORS 问题即将到来。

更新:我们部署在不同的服务器上,即 http:// 应用程序工作正常,但它在 https:// 上抛出错误

【问题讨论】:

  • response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000") 服务器也是这样吗?
  • local host:3000 是我的客户端应用程序部署的地方,服务器在 test.com
  • 你解决了吗?我也面临同样的问题。
  • 还没有@Thirumal。!
  • 它对我有用还添加了回答。看看@RameshKotha

标签: spring spring-mvc spring-security cors


【解决方案1】:

修改访问控制允许来源

 response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

并且,允许所有 HttpMethod.OPTIONS 请求。

    @Override
protected void configure(HttpSecurity http) throws Exception {
    //http.csrf().disable();
    http
        .csrf().disable()
        .httpBasic().and()
        .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .anyRequest().authenticated()
            //.and().requiresChannel().anyRequest().requiresSecure()
            .and().httpBasic().authenticationEntryPoint(customBasicAuthenticationEntryPoint)

            .and().addFilter(basicAuthenticationFilter(super.authenticationManagerBean()));
}

@ramesh-kotha,更多信息请查看CORS OPTION and GET

【讨论】:

  • 谢谢,会检查并通知您。!
猜你喜欢
  • 2021-04-04
  • 2014-10-17
  • 2015-07-22
  • 2018-04-20
  • 2014-07-20
  • 1970-01-01
相关资源
最近更新 更多