【问题标题】:Rails: How to implement protect_from_forgery in Rails API modeRails:如何在 Rails API 模式下实现protect_from_forgery
【发布时间】:2017-08-05 08:06:17
【问题描述】:

我有一个 Rails 5 API 应用程序 (ApplicationController < ActionController::API)。需要为此 API 的一个端点添加一个简单的 GUI 表单。

最初,当我尝试渲染表单时,我收到了ActionView::Template::Error undefined method protect_against_forgery?。我将include ActionController::RequestForgeryProtectionprotect_from_forgery with:exception 添加到该端点。正如预期的那样解决了这个问题。

但是,当我尝试提交此表单时,我得到:422Unprocessable EntityActionController::InvalidAuthenticityToken。我添加了<%= csrf_meta_tags %> 并验证了meta: csrf-parammeta: csrf-token 存在于我的标题中,并且authenticity_token 存在于我的表单中。 (令牌本身彼此不同。)

我试过了,protect_from_forgery prepend: true, with:exception,没有效果。我可以通过注释掉“解决”这个问题:protect_from_forgery with:exception。但我的理解是,这会关闭我表单上的 CSRF 保护。 (我想要 CSRF 保护。)

我错过了什么?

更新:

为了澄清这一点,这个应用程序的 99% 是纯 JSON RESTful API。需要向这个应用程序添加一个 HTML 视图和表单。所以对于一个控制器我想启用完整的 CSRF 保护。应用的其余部分不需要 CSRF,可以保持不变。

更新 2:

我只是将这个应用程序的 HTML 表单和 Header 的页面源与我编写的另一个常规 Rails 5 应用程序进行了比较。 Header 中的 authenticity_token 和表单中的 authenticity_token相同。在我遇到问题的 API 应用程序中,它们是不同的。也许是这样?

更新 3:

好的,我不认为不匹配是问题所在。然而,在工作应用程序和非工作应用程序之间的进一步比较中,我注意到网络 > Cookies 中没有任何内容。我在工作应用的 cookie 中看到了很多类似 _my_app-session 的东西。

【问题讨论】:

    标签: ruby-on-rails security csrf ruby-on-rails-5


    【解决方案1】:

    如果您使用的是 Rails 5 API 模式,则不要在任何视图中使用 protect_from_forgery 或包含 <%= csrf_meta_tags %>,因为您的 API 是“无状态”的。如果您打算使用完整的 Rails(不是 API 模式),同时也将其用作其他应用程序/客户端的 REST API,那么您可以执行以下操作:

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

    以便在适当的时候调用protect_from_forgery。但是我在您的代码中看到了ActionController::API,所以看起来您正在使用 API 模式,在这种情况下,您将完全从应用程序控制器中删除该方法

    【讨论】:

    • 应用程序一个纯 RESTful API,所有 json。现在需要向这个应用程序添加一个 HTML 视图和表单。所以,只针对那个控制器我想退出 API 模式并启用 CSRF 保护。
    • 我确实尝试过这个解决方案,但当我尝试发布表单时仍然收到Can't verify CSRF token authenticity....
    • 在您看来,您是否使用erb 并且您的表单是否使用<%= form_tag %>
    • ApplicationController 扩展了 ActionController::API,那么您的控制器是否扩展了 ApplicationController?如果是这样,请尝试将其更改为 class MyController < ActionController::Base
    • 试一试,同样的错误。 InvalidAuthenticityToken
    【解决方案2】:

    AJAX 调用和 API 不需要protect_from_forgery。

    如果您想为某些操作禁用它,那么

    protect_from_forgery except: ['action_name']
    

    【讨论】:

    • 是的,我的问题是如何为一个控制器的 -API 调用激活它?我有 一个 HTML 页面和我想要 CSRF 保护的表单,应用程序的其余部分是 RESTful JSON API,不需要它。我假设将protect_from_forgery 添加到那个控制器,以及include ActionController::RequestForgeryProtection 会这样做,但现在我在尝试提交该表单时得到InvalidAuthenticityToken
    • 你们真的确定不需要 API 中的 CSRF 保护只需要 Ajax 调用和 cookie 吗?
    • 如何保护 API?
    【解决方案3】:

    问题出在:Rails 5 在 API 模式下,逻辑上不包括 Cookie 中间件。没有它,就没有 Session key 存储在 Cookie 中以在验证我通过表单传递的令牌时使用。

    有点令人困惑,更改 config/initializers/session_store.rb 中的内容没有任何效果。

    我最终在这里找到了该问题的答案:Adding cookie session store back to Rails API app,这将我带到了这里:https://github.com/rails/rails/pull/28009/files,它准确地提到了我需要添加到 application.rb 以恢复正常工作的 Cookie 的行:

    config.session_store :cookie_store, key: "_YOUR_APP_session_#{Rails.env}"
    config.middleware.use ActionDispatch::Cookies # Required for all session management
    config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
    

    这三行加上:

    class FooController < ApplicationController
      include ActionController::RequestForgeryProtection
      protect_from_forgery with: :exception, unless: -> { request.format.json? }
      ...
    

    当然还有一个通过适当的助手生成的表单:

    form_tag(FOO_CREATE_path, method: :post)
      ...
    

    在我的 Rails API 应用程序中获得了一个受 CSRF 保护的表单。

    【讨论】:

    • 不清楚为什么首先需要在 API 模式下使用 form_tag。 API 模式的想法是将您的后端作为纯数据端点,而不负责生成任何 UI 表示。
    • @FabrizioBertoglio 不,这既不是我说的,也不是你的说法。您可能需要担心 API 应用程序中的 CSRF 攻击。您需要担心 CSRF 的一个例子是,当您的 API 服务使用 cookie 时。
    • 现在我得到 NoMethodError (undefined method `flash=' for #<:request:0x00007f8d66bbe0b8>): using rails 5.1.7 api only app.似乎添加 config.middleware.use ActionDispatch::Flash 有帮助。
    • request.format.json? 不是您想要的支票。请求者可以通过将.json 添加到他们有跨源表单发布到的 url 的末尾来绕过它。您需要request.content_type ~= /json/,它将检查请求的内容类型标头,浏览器将阻止跨源请求在没有 CORS 预检的情况下进行。
    【解决方案4】:
    class Api::ApiController < ApplicationController
      skip_before_action :verify_authenticity_token
    end
    

    如上使用 rails 5

    【讨论】:

      【解决方案5】:

      我在开发仅使用 Rails 6 API 的应用程序时遇到了这个挑战。

      我是这样解决的

      首先,将其包含在您的 app/controllers/application_controller.rb 文件中:

      class ApplicationController < ActionController::API
        include ActionController::RequestForgeryProtection
      end
      

      注意:添加这是因为protect_from_forgeryActionController::RequestForgeryProtection 中包含的类方法,在API 模式下使用Rails 时不可用。

      接下来,添加跨站请求伪造保护:

      class ApplicationController < ActionController::API
        include ActionController::RequestForgeryProtection
      
        protect_from_forgery with: :null_session
      end
      

      或者,如果您想根据请求格式有条件地保护_from_forgery:

      class ApplicationController < ActionController::API
        include ActionController::RequestForgeryProtection
      
        protect_from_forgery with: :exception if proc { |c| c.request.format != 'application/json' }
        protect_from_forgery with: :null_session if proc { |c| c.request.format == 'application/json' }
      end
      

      最后,将下面的行添加到您的config/application.rb 文件中。将其添加到 class Application &lt; Rails::Application 类中,就在底部:

      config.middleware.use ActionDispatch::Flash
      

      所以它看起来像这样:

      module MyApp
        class Application < Rails::Application
          # Initialize configuration defaults for originally generated Rails version.
          config.load_defaults 6.1
      
          # Configuration for the application, engines, and railties goes here.
          #
          # These settings can be overridden in specific environments using the files
          # in config/environments, which are processed later.
          #
          # config.time_zone = "Central Time (US & Canada)"
          # config.eager_load_paths << Rails.root.join("extras")
      
          # Only loads a smaller set of middleware suitable for API only apps.
          # Middleware like session, flash, cookies can be added back manually.
          # Skip views, helpers and assets when generating a new resource.
          config.api_only = true
      
          config.middleware.use ActionDispatch::Flash
        end
      end
      

      注意:这将防止出现以下错误:

      NoMethodError (undefined method `flash=' for #<ActionDispatch::Request:0x0000558a06b619e0>):
      

      就是这样。

      我希望这会有所帮助

      【讨论】:

        猜你喜欢
        • 2015-03-12
        • 2014-07-09
        • 2019-09-15
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 2011-07-26
        相关资源
        最近更新 更多