Rails 5 API protect_from_forgery

los*_*her 21 security ruby-on-rails csrf ruby-on-rails-5

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

最初我ActionView::Template::Error undefined method protect_against_forgery?在尝试渲染表单时得到了.我添加include ActionController::RequestForgeryProtectionprotect_from_forgery with:exception到终点.哪个问题按预期解决了.

但是,当我尝试提交此表格时,我得到:422 Unprocessable Entity ActionController::InvalidAuthenticityToken.我添加<%= csrf_meta_tags %>并验证了它meta: csrf-param并且meta: 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应用程序进行了比较.的authenticity_token页眉和authenticity_token形式是相同的.在我遇到问题的API应用程序中,它们是不同的.也许那是什么?

更新3:

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

los*_*her 23

这就是问题所在:Rails 5,在API模式下,逻辑上不包括Cookie中间件.没有它,key在验证我通过表单传递的令牌时,Cookie中不存储会话.

有点令人困惑的是,改变一切config/initializers/session_store.rb都没有效果.

我最终在这里找到了这个问题的答案:将cookie会话存储添加回Rails API应用程序,这导致我在这里: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
Run Code Online (Sandbox Code Playgroud)

这三行加上:

class FooController < ApplicationController
  include ActionController::RequestForgeryProtection
  protect_from_forgery with: :exception, unless: -> { request.format.json? }
  ...
Run Code Online (Sandbox Code Playgroud)

当然,通过适当的帮助者生成的表格:

form_tag(FOO_CREATE_path, method: :post)
  ...
Run Code Online (Sandbox Code Playgroud)

在我的Rails API应用程序中间获得了一张CSRF保护表单.

  • 首先,尚不清楚为什么需要在 API 模式下使用 form_tag。API 模式的想法是让您的后端作为纯数据端点,而不负责生成任何 UI 表示。 (2认同)

Ric*_*own 17

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

protect_from_forgery unless: -> { request.format.json? }
Run Code Online (Sandbox Code Playgroud)

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


Pro*_*ton 7

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

我是这样解决的

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

class ApplicationController < ActionController::API
  include ActionController::RequestForgeryProtection
end
Run Code Online (Sandbox Code Playgroud)

注意:添加此内容protect_from_forgery是因为其中包含一个类方法,ActionController::RequestForgeryProtection在 API 模式下使用 Rails 时该方法不可用。

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

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

  protect_from_forgery with: :null_session
end
Run Code Online (Sandbox Code Playgroud)

或者如果您想根据请求格式有条件地保护免受伪造:

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
Run Code Online (Sandbox Code Playgroud)

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

config.middleware.use ActionDispatch::Flash
Run Code Online (Sandbox Code Playgroud)

所以它看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

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

NoMethodError (undefined method `flash=' for #<ActionDispatch::Request:0x0000558a06b619e0>):
Run Code Online (Sandbox Code Playgroud)

就这样。

我希望这有帮助