如何关闭仅用于json的rails protect_from_forgeryfilter
我有使用Rails3构建的网站,现在我想为移动客户端访问实现json API。 但是,由于protect_from_forgeryfilter,从客户端发送json post请求。 因为客户端不会从服务器检索任何数据,所以客户端无法接收auth_token,因此我只想为json请求关闭protect_from_forgery选项(我认为rails3在默认情况下执行此操作,但显然它没有) 。
我知道在这里讨论类似的主题,但在这种情况下,他在发送post请求之前收到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 -一世
看一下这篇文章:http: //zadasnotes.blogspot.com/2010/11/rails-3-forgery-csrf-protection-for.html
更新
从那时起,该文章已被删除,所以我做了一个快速搜索,我发现该文章的原始作者在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
您可以在表单中传递authenticity_token字段,而不是禁用CSRF检查,例如:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
将以下代码添加到./app/controllers/application_controller.rb
:
protect_from_forgery unless: -> { request.format.json? }