【问题标题】:Spring Security REST CORS withCredentials A wildcard '*'Spring Security REST CORS withCredentials 通配符“*”
【发布时间】:2015-03-22 06:20:58
【问题描述】:

我正在尝试使用 Spring Security 设置 Spring Boot 应用程序并公开 REST 服务。

我在这里添加了建议的 CORS 过滤器:https://spring.io/guides/gs/rest-service-cors/ 但这似乎还不够。

代码:

@Component
public class CrossOriginRequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization");
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {

    }
}

jQuery 请求如下所示:

var bytes = btoa("admin" + ":" + "admin");

$.ajax({
type: 'GET',
url: '[url removed]',
headers: {"Authorization": "Basic " + bytes},
xhrFields: {
    withCredentials: true
},
success: function(a,b,c) {
console.log(a);
console.log(b);
console.log(c);
},
error: function (e1,e2,e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});

我收到此错误: XMLHttpRequest 无法加载 [url 省略]。当凭证标志为真时,不能在“Access-Control-Allow-Origin”标头中使用通配符“*”。 Origin 'http://localhost:8080' 因此不允许访问。

P.S:我从 localhost:8080 访问远程服务器,猜猜这就是为什么它在 Origin 中这样说的原因。

有人知道我错过了什么吗? 在 Stack 看到一些代码,人们检查它是否是一个 OPTIONS 请求,但我没有找到 ServletRequest.getMethod,此外,它似乎有点 hacky?

【问题讨论】:

  • 你是用tomcat来部署的吗?
  • Jetty 8,来自 Spring Boot

标签: jquery spring-security cross-domain spring-boot


【解决方案1】:

请查看最新发布的 Spring Boot 1.3.M1: https://spring.io/blog/2015/06/12/spring-boot-1-3-0-m1-available-now

最近发布的 Spring Framework 4.2 RC1 为 CORS 提供了开箱即用的一流支持,与典型的基于过滤器的解决方案相比,为您提供了一种更简单、更强大的配置方式。

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin(origin = "http://domain2.com")
    @RequestMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

...以及更多:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

【讨论】:

  • Spring Framework CORS 内置支持处理此用例。它允许您配置* 允许的来源,并且当需要像问题中那样需要凭据时,它将使用Origin 标头中提供的域来设置Access-Control-Allow-Origin 响应标头值的请求。
猜你喜欢
  • 2019-04-24
  • 2017-02-16
  • 2018-03-06
  • 2018-06-21
  • 2014-07-10
  • 2019-07-16
  • 1970-01-01
  • 2015-03-29
  • 2019-05-09
相关资源
最近更新 更多