【问题标题】:Expire a Session after Closing the Browser OR after 30 Minutes in Rails?在关闭浏览器后或在 Rails 中 30 分钟后过期会话?
【发布时间】:2019-08-26 00:02:22
【问题描述】:

如何在用户关闭浏览器或 30 分钟后使 Rails 中的会话过期?以先到者为准?

我尝试在session_store.rb 设置expire_after: nil || 30.minutes 但不起作用。

Rails 3.2

【问题讨论】:

  • 你在使用 devise gem 吗?
  • @sam 不,我不是
  • 好的,那你可以试试我的回答。

标签: ruby-on-rails ruby session


【解决方案1】:

您可以在初始化文件config/initializers/session_store.rb

中配置应用程序的会话信息
YourApp::Application.config.session_store :cookie_store, 
  :key => '_my_session', 
  :expire_after => 30.minutes

如果您正在使用,那么 Devise 有一个您可以使用的可超时模块。

在您的用户模型中,您将在您的设计模型中包含 :timeoutable,在 devise.rb 初始化程序中,您可以将其配置为:

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  config.timeout_in = 30.minutes

您必须在选项中添加具有 nil 值的 expire_after 键:

Rails.application.config.session_store :cookie_store, key: '_app_session', expire_after: nil

应用此更改后,会话将在用户关闭浏览器时过期。您可以阅读更多关于 cookie 过期的信息here

【讨论】:

  • 这只会在 30 分钟后使会话过期。如果用户关闭浏览器,我希望它也过期。 ?
  • 您必须在选项中添加具有 nil 值的 expire_after 键:Rails.application.config.session_store :cookie_store, key: '_app_session', expire_after: nil
  • 嗯,是的,我在 SO 中浏览了那个 wiki 和其他答案,但关键是我希望会话在 30 分钟后过期或浏览器关闭
  • @Pants 默认关闭浏览器,只要你没有自定义会话,会话就会被销毁。
  • @7urkm3n 我的问题似乎与缓存问题有关。感谢您的帮助。
【解决方案2】:

好的,所以问题在于缓存。我必须限制登录页面上的缓存,以避免显示主页时出现延迟,就像用户已登录一样。

在 application_controller.rb 我设置了以下内容:

before_filter :set_cache_headers
def set_cache_headers
      expires_now
end

在 session_store.rb 中,我将会话存储设置为

expire_after: 30.minutes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-18
    • 2010-10-05
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    相关资源
    最近更新 更多