2017-04-11 155 views
4

背景细节的ActionController :: InvalidAuthenticityToken Rails的5 /设计/审计/ PaperTrail宝石

我使用设计进行身份验证登录到一个Rails的5应用。

每当我捆绑要么审计纸径宝石,当我尝试#创建一个新的会话(通过形式符号 - /用户/ sign_in),我收到以下错误:

ActionController::InvalidAuthenticityToken 

环境细节

红宝石2.3.1

宝石:

  • 导轨 5.0.2
  • 设计 => 4.2.1
  • paper_trail => 7.0.1

重现步骤:

  1. 创建的Rails 5应用
  2. 添加设计的宝石
  3. 添加审计或纸径宝石
  4. 尝试登录
+1

您是否在application_controller中使用':exception'保护了'protect_from_forgery? – whodini9

+2

@ whodini9 - 宾果。这是错误的原因。我把它改为: 'protect_from_forgery prepend:true' 然后事情很开心。谢谢您的帮助。 – aldefouw

回答

15

事实证明,设计文档相当关于此错误显露:

For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.

该修复程序是从我的应用程序控制器中更改代码:

protect_from_forgery with: :exception 

要这样:

protect_from_forgery prepend: true 

这个问题并没有显现出来,直到我试图将经过审计或纸径宝石。

+0

为我工作,奇怪的是,如果您仍然登录,问题不会出现,所以它似乎是间歇性的。 – Steve

+1

@JohnLinux - 我经历过同样的事情。 虽然我不认为这是间歇性的。我认为当你登录时Devise会通过不同的调用堆栈发送给你。 – aldefouw

+0

这给我造成了很多困惑和沮丧。多个其他帖子提到'移动'它,但非特定的前置。谢谢。 – DNorthrup

0

在我的项目中,我们有这个问题,我们不能覆盖 protect_from_forgery。 建立的解决方案是指示审计和为我工作的github。

把这个在Gemfile中:

gem "audited", github: "collectiveidea/audited" 
+1

这似乎不是OP问题的答案? – LethalProgrammer

+1

@LethalProgrammer,对不起,我不明白OP的问题。我的答案是没有编辑_protect_from_forgery_,因为我的项目使用before_action回调在会话创建之前验证某些东西。对不起,如果我的答案不清楚。 – msfreire

+0

@msfreire - 如果你使用你发布的github分支,你是否建议你可以在应用程序控制器中使用'protect_from_forgery::exception' ? – aldefouw

0

documentation提及。

对于Rails 5,请注意protect_from_forgery不再作为before_action链的前缀,因此如果您在protect_from_forgery之前设置了authenticate_user,那么您的请求将导致“无法验证CSRF令牌的真实性”。要解决此问题,请更改您调用它们的顺序,或者使用protect_from_forgery prepend:true。

我已经使用过这样的东西,它适用于我。

class WelcomeController < ::Base 
    protect_from_forgery with: :exception 
    before_action :authenticate_model! 
end 
相关问题