如何关闭仅适用于json的railsprotect_from_forgery过滤器

|| 我有一个用Rails3构建的网站,现在我想实现JSON API来访问移动客户端。但是,由于protect_from_forgery过滤器,从客户端发送json发布请求。因为客户端不会从服务器检索任何数据,所以客户端无法接收auth_token,所以我只想对json请求关闭protect_from_forgery选项(我以为rails3在默认情况下会这样做,但显然不会) 。 我知道这里讨论了类似的话题,但是在那种情况下,他在发送发布请求之前收到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 \“内容类型:application / json \” -c cookies.txt -d \'{\“ email \”:emailVal,\“ password \”:passwordVal} \'-X POST http:// www .example.com / login.json -i
已邀请:
看一下这篇文章:http://zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html [archive.org] 更新资料 此后该文章已被删除,因此我进行了快速搜索,发现该文章的原始作者在SO上发布了此问题。 Rails 3 AJAX请求真实性令牌被忽略
您可以跳过真实性令牌检查,如果它是json请求
class ApplicationController < ActionController::Base
  skip_before_filter :verify_authenticity_token, if: :json_request?

  def json_request?
    request.format.json?
  end
end
除了禁用CSRF检查,您还可以在表单中传递authenticity_token字段,例如:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
http://apidock.com/rails/v2.0.0/ActionController/RequestForgeryProtection/ClassMethods/protect_from_forgery
将以下代码添加到您的
./app/controllers/application_controller.rb
中:
protect_from_forgery unless: -> { request.format.json? }

要回复问题请先登录注册