我有一个 Rails 5 API 应用程序 ( ApplicationController < ActionController::API
)。需要为此 API 的一个端点添加一个简单的 GUI 表单。
最初,我得到 ActionView::Template::Error undefined method protect_against_forgery?
当我尝试渲染表单时。我添加了include ActionController::RequestForgeryProtection
和protect_from_forgery with:exception
到那个端点。这按预期解决了该问题。
但是,当我尝试提交此表单时,我得到:422
Unprocessable Entity
ActionController::InvalidAuthenticityToken
。我添加了<%= csrf_meta_tags %>
并验证了 meta: csrf-param
和meta: csrf-token
出现在我的标题中,并且 authenticity_token
存在于我的表格中。 ( token 本身彼此不同。)
我试过了,protect_from_forgery prepend: true, with:exception
, 没有效果。我可以通过注释掉来“修复”这个问题:protect_from_forgery with:exception
。但我的理解是,这会关闭我表单上的 CSRF 保护。 (我想要 CSRF 保护。)
我错过了什么?
更新:
为了澄清这一点,这个应用程序的 99% 是纯 JSON RESTful API。需要向此应用程序添加一个 HTML View 和表单。因此,对于一个 Controller ,我想启用完整的 CSRF 保护。应用程序的其余部分不需要 CSRF 并且可以保持不变。
更新2:
我只是将此应用程序的 HTML 表单和页眉的页面源代码与我编写的另一个传统 Rails 5 应用程序进行了比较。 authenticity_token
在标题和 authenticity_token
形式相同。在我遇到问题的 API 应用程序中,它们是不同的。也许这就是什么?
更新3:
好吧,我不认为不匹配是问题所在。然而,在工作和非工作应用程序之间的进一步比较中,我注意到“网络”>“Cookies”中没有任何内容。我看到了很多类似 _my_app-session
的东西在工作应用程序的 cookie 中。
最佳答案
问题是这样的:Rails 5 在 API 模式下,逻辑上不包含 Cookie 中间件。如果没有它,在验证我通过表单传递的 token 时,就不会在 Cookie 中存储 session key
。
有点令人困惑的是,更改 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 保护的表单。
关于ruby-on-rails - rails : How to implement protect_from_forgery in Rails API mode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42795288/