【问题标题】:Can't verify CSRF token authenticity when using prepend_before_action使用 prepend_before_action 时无法验证 CSRF 令牌的真实性
【发布时间】:2018-02-14 05:57:15
【问题描述】:

我有以下应用程序控制器。我最近添加了我想在授权部分之前执行的 set_customer。 prepend_before_action 完美地做到了这一点。但是,一旦添加该行,我就会收到此错误:无法验证 CSRF 令牌真实性

current_user 不是 nil,所以当我调试它时,它会直接通过 set_customer 部分并直接进入授权方法。当我删除 prepend_before_action 行时,它再次起作用。我该如何解决这个问题(当然要保持 CSRF 保护。

也许需要提一下:我也在使用设计。 Devise::SessionsController#create

出现错误
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception, prepend: true
  before_action :authorize
  prepend_before_action :authorize, :set_customer

  def authorize
    if current_permission.allow?(params[:controller], params[:action], current_resource)
      current_permission.permit_params! params
    else
      raise Permission::NotAuthorized
    end
  end

  def set_customer
    if current_user.nil?
      # some unimportant code since current_user isn't nil
    end
  end

【问题讨论】:

  • 你试过将protect_from_forgery移动到prepend_before_action下面吗? Devise GitHub 上针对 CSRF 错误的建议之一是更改您调用它们的顺序,或将 prepend 添加到 p_f_p。据我了解,prepend 将要添加的内容设置为索引 0。这会将您的 authorize 调用放在执行 p_f_p 调用之前。只是一个想法。
  • @josh 成功了!谢谢,如果你在这里添加它作为答案,我会接受它。

标签: ruby-on-rails


【解决方案1】:

您是否尝试将protect_from_forgery 移动到prepend_before_action 下方? Devise GitHub 上针对 CSRF 错误的建议之一是更改您调用它们的顺序,或将 prepend 添加到 p_f_p。据我了解, prepend 会将要添加的内容设置为索引 0。这会将您的授权调用放在执行 p_f_p 调用之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 2015-07-24
    • 2014-06-16
    • 2012-05-08
    • 2015-12-29
    • 2023-03-26
    • 2016-09-17
    • 2017-07-19
    相关资源
    最近更新 更多