【问题标题】:How to turn off rails protect_from_forgery filter only for json如何仅针对 json 关闭 railsprotect_from_forgery 过滤器
【发布时间】:2011-08-08 16:53:44
【问题描述】:

我有一个使用 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

【问题讨论】:

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


    【解决方案1】:

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

    class ApplicationController < ActionController::Base
      skip_before_filter :verify_authenticity_token, if: :json_request?
    
      def json_request?
        request.format.json?
      end
    end
    

    【讨论】:

    • 请注意,这使得它容易受到 csrf 的攻击。
    • 在 Rails 5+ 上使用 skip_before_action
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
      

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

      【讨论】:

      • 如果 UI 完全在不同的项目中构建,这可能是不可能的
      猜你喜欢
      • 2012-08-28
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 2016-03-22
      • 2013-08-31
      • 2010-11-01
      • 1970-01-01
      相关资源
      最近更新 更多