【问题标题】:Rails 3 AJAX request authenticity token ignoredRails 3 AJAX请求真实性令牌被忽略
【发布时间】:2011-05-05 22:23:10
【问题描述】:

Rails 似乎忽略了 AJAX 请求的真实性令牌。例如,我故意更改了我的 AJAX 调用以使用无效令牌进行测试,并且请求似乎正常通过。

应用程序具有使用会话 cookie 存储的默认配置,并在 ApplicationController 中调用了protect_from_forgery。

还有什么我可能会遗漏的想法吗?

【问题讨论】:

    标签: jquery ajax ruby-on-rails-3 csrf


    【解决方案1】:

    编辑 >> 我也在一篇博文中发布了这个答案:http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html [archive.org]

    EDIT 2 >> 这在 Rails 3.0.4 中有所改变。在此处查看后续帖子:http://zadasnotes.blogspot.com/2011/02/rails-forgery-csrf-protection-for-ajax.html [archive.org]

    在研究了一段时间后,我决定深入研究一下 rails 代码文档以找出答案。

    从这里开始:http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html#method-i-form_authenticity_token

    protect_from_forgeryverify_authenticity_token 上添加一个 before_filter,如下所示:

    # File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 95
    95:       def verify_authenticity_token
    96:         verified_request? || raise(ActionController::InvalidAuthenticityToken)
    97:       end
    

    verified_request? 显示在这里:

    # File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line   
    104:       def verified_request?
    105:         !protect_against_forgery? || request.forgery_whitelisted? ||
    106:           form_authenticity_token == params[request_forgery_protection_token]
    107:       end
    

    终于request.forgery_whitelisted?

       # File actionpack/lib/action_dispatch/http/request.rb, line 126
    126:     def forgery_whitelisted?
    127:       get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request?
    128:     end
    

    通知 xhr?。 xmlHttpRequest 被列入白名单并且不在protect_from_forgery 列表中。因此,这似乎是设计使然。

    在对 xmlHttpRequests 进行进一步研究后,似乎在跨域运行它们时存在限制,这使得没有必要对 xhr 应用 csrf 检查。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2013-04-21
    • 1970-01-01
    • 2011-03-04
    相关资源
    最近更新 更多