Rails 5.2 ActionController::InvalidAuthenticityToken Rails 5.2中的ActionController::InvalidAuthenticityToken

6

在升级到Rails 5.2后,我开始在应用程序的所有表单中收到一个ActionController::InvalidAuthenticityToken错误。我通过禁用所有表单的Turbolinks来解决了这个问题,虽然可以工作,但不是一个很好的解决方案。

在搜索互联网时,推荐的常见解决方案似乎是禁用protect_from_forgery

skip_before_action :verify_authenticity_token, raise: false

我们为什么需要禁用protect_from_forgery,这是否会造成安全漏洞?

编辑

csrf_meta_tags在布局中。

enter image description here

2个回答

10

对于Rails 5.2,在ActionController::Base默认启用default_protect_from_forgery

您可以使用以下语法禁用它,如PR中所述

config.action_controller.default_protect_from_forgery = false

参考自文档

config.action_controller.default_protect_from_forgery决定是否在ActionController:Base上添加防伪保护。默认情况下为false,但在加载Rails 5.2的默认设置时启用。


1
谢谢您提供这个信息,但是如果设置了这个选项,应用程序现在不是容易受到 CSRF 攻击吗? - port5432
您可以在ApplicationController中使用protect_from_forgery。如果它再次生成错误,则可能在某个地方错过了meta标签,可能是在AJAX调用中。 - Kartikey Tanna
默认设置在ActionController::Base上,这就是为什么你使用的某些外部库可能会导致错误。在ApplicationController中设置protect_from_forgery将使您的控制器更加安全。 - Kartikey Tanna

2

对于Rails 5.2,我在控制器内遇到了问题,必须添加以下两行代码:

  skip_before_action :verify_authenticity_token, raise: false
  skip_after_action :verify_authorized

而且在我的情况下它起作用了。


1
仅使用第一行对我有效。 - DivinesLight

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接