【问题标题】:session become nil in application controllersession 在应用程序控制器中变为 nil
【发布时间】:2016-07-17 14:48:34
【问题描述】:

在我们的 Rails 4.2 应用程序中,模块的应用程序控制器中的方法 view_handler 使用 session 变量获取 nil。代码结构如下:

class my_module < ApplicationController
  def view_handler
    #access session[:page_step] which is defined in controller.
  end
end 

会话使用默认 cookie 存储:

Rails.application.config.session_store :cookie_store, key: '_my_app_session'

我们验证这不是scope 问题,因为当view_handler 移动到主应用程序的application controller 时问题仍然存在。

在使用application controller 进行调试时,session 对象存在但具有nil 值:

>session.present? #false
>session.nil? #true
>session[:page_step] #nil

这是调试中的session 对象。保存应用定义的会话变量的@delegate 为空:

同样在调试中,session[:page_step]controller 操作的后期再次出现。不知何故,session[:page_step](和其他会话变量)在application controller 中变为nil,并在controller 中重新出现。由于默认情况下application controller 中的session variablesRAILS 中可用,是什么导致它们在application controller 中变为nil?

【问题讨论】:

标签: ruby-on-rails session


【解决方案1】:

您可能遇到CSRF Issue

如果安全令牌与预期不符,会话将被重置

要检查是否是 CSRF 问题,您可以暂时禁用 ApplicationController 中的 protect_from_forgery

此外,请确保您的 Session Storage 配置完整,config/secrets.yml 中的密钥用于非生产环境并作为生产环境变量。

可以在控制台中按如下方式生成密钥:

$ rake secret
82d58d3dfb91238b495a311eb8539edf5064784f1d58994679db8363ec241c745bef0b446bfe44d66cbf91a2f4e497d8f6b1ef1656e3f405b0d263a9617ac75e

每次使用新密钥时,使用其他密钥的旧会话将不会生效,会话结果将为 nil。

直接从生成的文件config/secrets.yml(Rails 4.2)评论:

# Be sure to restart your server when you modify this file.

# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!

# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.

# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.

【讨论】:

  • 在 Rails 应用程序中删除 protect_from_forgery with: :exception,重新启动服务器,会话问题仍然存在。有用于开发、测试和生产的 secret_key_bases。还有什么可能导致重置会话?
  • 您是否尝试过所有主流浏览器以重现此问题?全新安装(无扩展或附加组件)效果最佳。
  • firefox 和 IE 都有同样的问题。代码用了很久,不知道是什么原因造成的。
猜你喜欢
  • 2014-01-06
  • 2014-06-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
相关资源
最近更新 更多