如何关闭仅用于json的rails protect_from_forgery过滤器

时间:2011-04-19 13:38:18

标签: ruby-on-rails ajax json rest protect-from-forgery

我有使用Rails3构建的网站,现在我想为移动客户端访问实现json API。但是,由于protect_from_forgery过滤器,从客户端发送json post请求。因为客户端不会从服务器检索任何数据,所以客户端无法接收auth_token,因此我想仅为json请求关闭protect_from_forgery选项(我认为rails3在默认情况下执行此操作,但显然它没有)

我知道在here讨论了类似的话题,但在这种情况下,他在发送帖子请求之前收到了auth_token。

所以我的问题是只关闭json的protect_from_forgery是这样做的好方法吗?如果是,怎么办?如果不是,还有什么选择?

仅供参考,我使用以下ajax请求

$.ajax({
             type: 'POST',  
             url: "http://www.example.com/login.json",  
             data: { 'email': emailVal, 'password': passwordVal },  
             success: onSuccess,  
             error: onError,  
             dataType: "json"  
});

我得到ActionController :: InvalidAuthenticityToken错误。

顺便说一句,遵循curl命令可以工作......
curl -H“Content-Type:application / json”-c cookies.txt -d'{“email”:emailVal,“password”:passwordVal}'-X POST http://www.example.com/login.json -i

4 个答案:

答案 0 :(得分:10)

如果是json请求,您可以跳过真实性令牌检查

class ApplicationController < ActionController::Base
  skip_before_filter :verify_authenticity_token, if: :json_request?

  def json_request?
    request.format.json?
  end
end

答案 1 :(得分:3)

看一下这篇文章:http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html

<强>更新

此后该文章已被删除,因此我进行了快速搜索,发现该文章的原始作者在SO上发布了此问题。

Rails 3 AJAX request authenticity token ignored

答案 2 :(得分:1)

您可以在表单中传递authenticity_token字段,而不是禁用CSRF检查,例如:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

http://apidock.com/rails/v2.0.0/ActionController/RequestForgeryProtection/ClassMethods/protect_from_forgery

答案 3 :(得分:0)

将以下代码添加到您的./app/controllers/application_controller.rb

protect_from_forgery unless: -> { request.format.json? }