【问题标题】:Rails 5 + Devise: ActionController::InvalidAuthenticityTokenRails 5 + 设计:ActionController::InvalidAuthenticityToken
【发布时间】:2017-08-06 18:21:47
【问题描述】:

我使用 Rails 5 和 Devise 创建了一个新应用,设置了身份验证,几周后一切正常。

今天尝试登录生产服务器,出现这个错误:

ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken

经过一番谷歌搜索,我发现我需要进行此更改:

class ApplicationController < ActionController::Base
  #protect_from_forgery with: :exception # because of Devise + Rails 5 behavior
  protect_from_forgery prepend: true  

  def after_sign_in_path_for(resource_or_scope)
    my_listings_path
  end

  def after_sign_out_path_for(resource_or_scope)
    root_path
  end  
end

在生产服务器上进行此更改并部署后,我尝试登录 - 并出错。但另一个不同 - 现在应用程序将我重定向到 my_listings_path(这都是正确的),但问题是我收到了这个错误:

NoMethodError: undefined method `listings' for nil:NilClass

所以我看看这里有什么问题,并且:

@listings = current_user.listings.order('id DESC')

这意味着current_user 是空的 (nil) -- 怎么会?另外,我在网站上的&lt;head&gt; 标签中有这个:

 <%= csrf_meta_tags %>

另一个注意事项 - 在 localhost 上,一切正常,但在生产服务器上,我不断收到这些错误消息。

有什么建议吗?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby devise


    【解决方案1】:

    如果你想让current_user 工作,你需要在你的控制器中设置before_action :authenticate_user!。 我猜它在 localhost 上为您工作的原因是因为您以某种方式在会话中设置了 current_user 。如果您尝试隐身模式,我认为它不起作用。

    【讨论】:

    • 我已经尝试过了 - 看起来当我设置 protect_from_forgery prepend: true 时,生产中的应用程序看不到用户已登录。
    • 我认为这可能是因为您正在使用prepend: true,请尝试切换回protect_from_forgery with: exception 以及before_action :authenticate_user! 回调。我有一个带有这些选项的 rails 5.1 应用程序,它在生产中正常运行。
    猜你喜欢
    • 2018-11-02
    • 2017-09-07
    • 2017-11-13
    • 2016-11-14
    • 2017-04-12
    • 2018-11-27
    • 2015-11-23
    • 2014-12-17
    • 2019-09-25
    相关资源
    最近更新 更多