的ActionController :: InvalidAuthenticityToken Rails的5 /设计/审计/ PaperTrail宝石
背景细节的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
重现步骤:
- 创建的Rails 5应用
- 添加设计的宝石
- 添加审计或纸径宝石
- 尝试登录
事实证明,设计文档相当关于此错误显露:
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
这个问题并没有显现出来,直到我试图将经过审计或纸径宝石。
在我的项目中,我们有这个问题,我们不能覆盖 protect_from_forgery。 建立的解决方案是指示审计和为我工作的github。
把这个在Gemfile中:
gem "audited", github: "collectiveidea/audited"
这似乎不是OP问题的答案? – LethalProgrammer
@LethalProgrammer,对不起,我不明白OP的问题。我的答案是没有编辑_protect_from_forgery_,因为我的项目使用before_action回调在会话创建之前验证某些东西。对不起,如果我的答案不清楚。 – msfreire
@msfreire - 如果你使用你发布的github分支,你是否建议你可以在应用程序控制器中使用'protect_from_forgery::exception' ? – aldefouw
如 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
您是否在application_controller中使用':exception'保护了'protect_from_forgery? – whodini9
@ whodini9 - 宾果。这是错误的原因。我把它改为: 'protect_from_forgery prepend:true' 然后事情很开心。谢谢您的帮助。 – aldefouw