基于 Rails cookie 的会话:混合会话范围和过期时间 [英] Rails cookie based sessions: mixing session scope with expiration times

查看:49
本文介绍了基于 Rails cookie 的会话:混合会话范围和过期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我以不同的方式问了这个问题这里 并没有得到答案,所以我将尝试重新表述它,因为这似乎是一个非常简单的问题.

So I've asked this question in a different way here and got no answers so I'm going to try to rephrase it, since this seems to be a very simple issue.

我有一个基于 cookie 的会话的 Rails 应用程序.默认情况下,它们没有任何 expires_at 时间戳,因此会话 cookie 的范围是会话".这是您的原始 Rails 会话内容.

I have a Rails app with cookie based sessions. By default they don't have any expires_at timestamps and so the scope of the session cookie is 'session'. This is your vanilla Rails sessions stuff.

现在我想创建一个演示用户"功能,我在 15 分钟后将用户踢出去.为此,我想在会话 cookie 上为 Time.now + 15.minutes 设置一个 expires_at

Now I want to create a 'demo user' functionality wherein I kick the user out after 15 mins. To accomplish this, I want to set an expires_at on the session cookie for Time.now + 15.minutes

 session[:expires_at] = Time.now + 15.minutes 

现在上面这段代码确实执行了,但它对 cookie 的作用域没有影响.范围仍然是会话".如何将范围从会话"更改为日期时间?

Now this above piece of code does execute, but it has no impact on the cookie's scope. The scope remains 'session'. How do I change the scope from being 'session' to being a datetime?

如果我在 production.rb 中将整个应用程序的会话配置为

If I configure my entire application's Session in the production.rb to be

 :expire_after =>  24.hours 

然后它会起作用...但问题是我想有选择地控制会话 cookie 的到期日期.

Then it will work... but the problem is that I want to selectively control the expiration date on the session cookie.

编辑:结果证明,当我设置 session[:expires_at] 时对 cookie 的范围没有影响的原因是因为后续请求正在破坏 session cookie 并将其重置回 session.仍然不确定该怎么做.

Edit: Turns out that the reason why there is no impact on the cookie's scope when I set the session[:expires_at] is because subsequent requests are clobbering the session cookie and resetting it back to session. Still not sure what to do about it.

推荐答案

也许不是依赖 cookie 过期(请参阅 "Ruby On Rails 安全指南" 关于为什么它不好),类似于 this answer,在会话本身中存储创建会话时的时间戳(比如 session[:created_at]),然后检查每个请求是否需要过期这些演示用户":

Perhaps instead of relying on cookie expiry (see section 2.9 in "Ruby On Rails Security Guide" on why it is bad), similar to this answer, store timestamp when session was created in the session itself (say session[:created_at]) and then check on each request if it needs to be expired for these 'demo users':

before_filter :check_session

def check_session
  # TODO: check session validity
  if session[:demo_user] && session[:created_at] > 15.minutes.ago
    reset_session
    # TODO: redirect to login page
  end
end

这篇关于基于 Rails cookie 的会话:混合会话范围和过期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆