【问题标题】:verify_authenticity_token has not been definedverify_authenticity_token 尚未定义
【发布时间】:2017-01-08 16:03:38
【问题描述】:

Ruby 版本 2.2.4,Rails 版本 5.0.0.1。

我被困在tutorial 的一部分,您在其中使用curl 测试登录。我收到一个错误

ArgumentError(在 process_action 回调之前:verify_authenticity_token 尚未定义)。

我在 session_controller 中使用了这段代码:

skip_before_action :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }

有人知道答案吗?

【问题讨论】:

  • 检查你的项目中是否存在verify_authenticit_token并将其更改为verify_authenticity_token
  • 抱歉,这不是问题所在。通过创建这个问题,我忘记了这个词的“y”。我更正一下,谢谢
  • 顺便说一句,在我的完整项目中,verify_authenticity_token 没有定义。但是我如何以及在哪里可以定义这个方法?不是在宝石里吗?
  • 别人有什么想法吗,为什么我得到这个错误:ArgumentError (Before process_action callback: verify_authenticity_token has not been defined)?
  • 确保在调用protect_from_forgery 之前不要调用此skip_before_action。只需将它移到您的应用程序控制器中。

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


【解决方案1】:

检查您的ApplicationController 是否有对protect_from_forgery 的调用,如下所示:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

实际上调用protect_from_forgery 会将verify_authenticity_token 添加到before_filter 列表中,您可以在其他控制器中跳过该列表。

请参阅protect_from_forgery documentation 了解更多信息。

【讨论】:

    【解决方案2】:

    升级到 Rails 5 后,我遇到了这个错误。我发现如果skip_before_action被同一个方法名多次调用,就会抛出这个异常。

    我的解决方法是在第二次调用 skip_before_filter 时添加参数 raise: false

    所以它在应用程序控制器中看起来像这样:

    skip_before_action :your_method_name, raise: false
    

    【讨论】:

      【解决方案3】:

      升级到 Rails 5 并部署到 Heroku 后,我遇到了这个错误。我无法在开发中重现它。

      API docs中给出了例子

      class ApplicationController < ActionController::Base
        protect_from_forgery unless: -> { request.format.json? }
      end
      

      对我来说,像上面那样添加unless: -&gt; { request.format.json? } 修复了我的堆栈炸弹。 raise: false 很遗憾没有。

      【讨论】:

      • 嗨,这是否允许未经身份验证访问其他路由?还是会影响其他事情?
      【解决方案4】:

      我通过设置修复它: config.action_controller.default_protect_from_forgery = true in config/application.rb

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多