【问题标题】:grails REST API with Spring Security core and CORS plugins not working for OPTIONS http method requests带有 Spring Security 核心和 CORS 插件的 grails REST API 不适用于 OPTIONS http 方法请求
【发布时间】:2013-10-29 03:55:46
【问题描述】:

尝试从 AngularJS 前端向其他服务器上的 Grails 2.3.1 RESTful 服务执行跨域请求 [CORS]。

对于任何跨域请求,AngularJS 首先发送 OPTIONS http 请求。

为了支持这一点,我在我的控制器中添加了以下方法来扩展 RestfulController

static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE", options: "OPTIONS", trace: "TRACE", head: "HEAD"]
    @Secured(value=['permitAll'], httpMethod='OPTIONS')
    def options() {
        log.debug("i am in options method")
        response.setHeader("Allow", "GET,POST,PUT,DELETE,OPTIONS,TRACE,HEAD")
        return
    }

对于下面的 cURL 命令,我的控制器上的 options() 方法永远不会被调用。 curl 总是得到 301 响应。

curl -H "Origin: http://example.com" -X OPTIONS --verbose http://localhost:8080/Console/tenants/1/spaces.xml

这是 Spring Security 核心插件中的错误还是我遗漏了什么?

我的环境由 Grails 2.3.1、Spring Security Core 和 ACL 2.0-RC1 插件和 CORS 插件 1.1.1 组成

【问题讨论】:

    标签: angularjs grails spring-security cors options


    【解决方案1】:

    这是因为浏览器会在您执行操作之前检查跨域请求。您可以使用 servlet 过滤器来做到这一点,或者只使用 CORS Grails plugin

    【讨论】:

    • 我正在使用 CORS Grails 插件。如果我发送静态页面请求,例如:[curl -H "Origin: example.com" -X OPTIONS --verbose localhost:8080/Console/index.html] 但是当我向 RestfulController URL 发送相同的 OPTIONS 请求时,例如:[localhost:8080/Console/tenants/1/spaces.xml],它总是获得 301 响应,其中包含对 auth url 的位置。不知道是RestfulController还是Spring Security Core Plugin引起的。
    • “不是一个有效的 http 方法”?严重地?你的意思是他们没有实现这个方法对吧?
    • @TobiasHagenbeek 我之前的回答不正确,OPTIONS 有效 - developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS,很难记住 2013 年回答的上下文:(
    • 呵呵,是的,很遗憾,我读了我的评论,听起来可能不像... :) 很高兴你在这么久之后仍然回来!
    【解决方案2】:

    使用最新的 CORS Grails 插件解决了这个问题。它包括一个拦截 OPTIONS 请求并提供响应的过滤器。

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2016-08-30
      • 2012-05-24
      • 2018-08-26
      • 2016-07-23
      • 2011-11-23
      • 2020-10-27
      • 1970-01-01
      • 2017-01-11
      相关资源
      最近更新 更多