Rails似乎忽略了AJAX请求的真实性令牌。例如,我故意改变我的AJAX调用以使用无效令牌测试它,并且请求似乎正常通过。
应用程序具有默认配置以使用会话cookie存储,并在ApplicationController中具有protect_from_forgery调用。
任何想法我还能错过什么?
答案 0 :(得分:7)
编辑>>我也在博客文章中发布了这个答案:http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html
EDIT 2>>这在Rails 3.0.4中已经改变。请在此处查看后续帖子:http://zadasnotes.blogspot.com/2011/02/rails-forgery-csrf-protection-for-ajax.html
经过一段时间的研究后,我决定深入研究一下rails代码文档。
protect_from_forgery 在 verify_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检查。