Rails:如何在RailsAPI模式下实现protect_from_forgery

Rails: How to implement protect_from_forgery in Rails API mode

我有一个 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-parammeta: csrf-token 存在于我的 headers 中,并且 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:

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

如果您正在使用 Rails 5 API 模式,您不会在任何视图中使用 protect_from_forgery 或包含 <%= csrf_meta_tags %>,因为您的 API 是'stateless'。如果你打算使用完整的 Rails(不是 API 模式),同时将它用作其他 apps/clients 的 REST API,那么你可以这样做:

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

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

AJAX 个调用和 API 不需要 protect_from_forgery。

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

protect_from_forgery except: ['action_name']

问题是这样的:Rails 5、在API模式下,逻辑上不包含Cookie中间件。没有它,就没有 Session key 存储在 Cookie 中,用于验证我通过表单传递的令牌。

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

我最终在这里找到了该问题的答案:Adding cookie session store back to Rails API app, which led me here: 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 保护的表单。

class Api::ApiController < ApplicationController
  skip_before_action :verify_authenticity_token
end

如上使用 rails 5

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

我是这样解决的:

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

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

注意:添加此内容是因为 protect_from_forgeryActionController::RequestForgeryProtection 中包含的 class 方法,在使用 Rails 在 API 模式下。

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

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

  protect_from_forgery with: :null_session
end

或者,如果您想根据请求格式有条件地protect_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 < Rails::Application class 内,就在底部:

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>):

就这些了。

希望对您有所帮助