如何停止重定向发送预检请求?

时间:2019-03-26 20:21:31

标签: ruby-on-rails cors csrf-protection

我发现六年前,以前的开发人员注释掉了以下代码行(Ruby,Rails):

#protect_from_forgery

我将其替换为默认值:

protect_from_forgery with: :exception

现在,当我注销时尝试将商品添加到购物车时,我神秘地收到以下错误消息:

Access to XMLHttpRequest at 'https://id.foo-staging.com/openid/checklogin?return_to=http%3A%2F%2Flocalhost.foo-staging.com%3A3000%2Fcart%2Fitems' (redirected from 'http://localhost.foo-staging.com:3000/cart/items') from origin 'http://localhost.foo-staging.com:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

由于以下几行,我确定发生了这种情况:

def get_user_identity_from_open_id_server
  redirect_to "#{OPEN_ID_PROVIDER_URL}/openid/checklogin?return_to=#{Rack::Utils.escape(request.url)}"
end

def open_id_authentication
  #stuff
  get_user_identity_from_open_id_server
end

before_filter :open_id_authentication

由于文档的原因,我非常了解是什么导致了飞行前请求。但是我认为我没有做任何事情。

* the request method is anything other than GET, HEAD, or POST
* you’ve set custom request headers other than Accept, Accept-Language, Content-Language, Content-Type, DPR, Downlink, Save-Data, Viewport-Width, or Width
* the Content-Type request header has a value other than application/x-www-form-urlencoded, multipart/form-data, or text/plain

因此,我的首要问题是如何确定触发预检请求的原因,然后也许我可以弄清楚如何防止其发生。这是我可以改变的情况,还是需要在id.foo-staging.com上进行某些更改(我没有访问权限,但可能会请合适的人为我修复)。

我整天都在谷歌搜索,对我来说似乎没有任何意义,尤其是因为我无法准确查明出什么问题。

我可以使用以下代码解决问题:

skip_before_filter :open_id_authentication, :only => [:create], :if => :current_user and :anonymous_cart

但是从安全角度来看,我必须假设这是不安全的?

ETA:这是我在Network标签上看到的此请求:

常规:

Request URL: https://id.foo-staging.com/openid/checklogin?return_to=http%3A%2F%2Flocalhost.foo-staging.com%3A3000%2Fcart%2Fitems Referrer Policy: no-referrer-when-downgrade

请求标头:

Provisional headers are shown Access-Control-Request-Headers: x-requested-with Access-Control-Request-Method: GET Origin: http://localhost.foo-staging.com:3000 Referer: http://localhost.foo-staging.com:3000/p/Product0/1?id=1&slug=Product0 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36

查询字符串参数:

return_to: http://localhost.foo-staging.com:3000/cart/items

我认为问题是x-requested-with请求标头。但我不知道该如何解决。

EATA:

Many JavaScript frameworks such as JQuery will automatically send this header along with any AJAX requests. This header cannot be sent cross-domain:

我想我唯一的选择就是弄清楚如何在不使用AJAX的情况下重写它?

1 个答案:

答案 0 :(得分:0)

要避免执行预检请求,您必须删除x-requested-with标头,但是出现的错误是因为预检调用中的响应位置与原点不同。 要解决此问题,请更新代码以使用重定向报告的新URL,从而避免重定向。