Googlebot在Rails 4.1上导致无效的跨源请求(COR)

时间:2014-07-11 22:08:42

标签: ruby-on-rails ruby-on-rails-4 cors csrf ruby-on-rails-4.1

如何在抓取网站时阻止Google导致此错误?除非安全,否则我对关闭“protect_from_forgery”不感兴趣。

[fyi] method=GET path=/users format=*/* controller=users action=show status=200 duration=690.32 view=428.25 db=253.06 time=  host= user= user_agent=Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) session= params={""} ()
[hmm] Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding. (pid:)
[fyi] method=GET path=/users/123/flag format=*/* controller=users action=flag status=500 error='ActionController::InvalidCrossOriginRequest:Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.' duration=26.50 time= host= user= user_agent= session= params= (pid)
[omg] ActionController::InvalidCrossOriginRequest (Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.):
actionpack (4.1.4) lib/action_controller/metal/request_forgery_protection.rb:217:in `verify_same_origin_request'

控制器以此回应

respond_to do |format|
    format.js { render template: 'users/flag', layout: "some_layout" }
end

我无法重新创建错误,当我通过浏览器执行此操作时似乎工作正常

到目前为止,我已经查看了以下资源,但大多数人似乎都建议盲目转向CSRF或者没有答案。


澄清: 应该保护该操作免受CSRF的影响,但我想阻止Google抓取它或者通过抓取页面生成错误。即。)我希望虚假的安全警告消失而不会实际损害我的安全功能。

2 个答案:

答案 0 :(得分:16)

Googlebot正在使用格式&#34; * / *&#34; (http://apidock.com/rails/Mime)并且应用程序呈现js,因为它是唯一可用的东西。由于它是远程的,它正确地导致无效的COR。

这可以使用以下方法重现:

curl -H "Accept: */*" https://www.example.com/users/123/flag

修复方法是让蜘蛛抓取一个html后备资源:

respond_to do |format|
  format.html { render template: 'users/flag' }
  format.js { render template: 'users/flag', layout: "some_layout" }
end

答案 1 :(得分:1)

根据&#34;远程标签的CSRF保护&#34;来自导轨指南:

如果是测试,您也在做客户端,请改为:

  

get:index,format :: js

要:

  

xhr:get,:index,format :: js

http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#csrf-protection-from-remote-script-tags

如果您想要使此路线跳过csrf检查,白色会使用以下内容列出路线:

protect_from_forgery :except => :create