“记住我”的实施在Rails应用程序中 [英] Implementation of "Remember me" in a Rails application

查看:100
本文介绍了“记住我”的实施在Rails应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Rails-app有一个带有记住我复选框的登录框。检查该框的用户即使在关闭浏览器后仍应保持登录状态。我通过在用户的会话中存储他们的id来跟踪用户是否登录。

My Rails-app has a sign in box with a "remember me" checkbox. Users who check that box should remain logged in even after closing their browser. I'm keeping track of whether users are logged in by storing their id in the user's session.

但会话在Rails中实现为会话cookie,而不是持久性的。我可以使持久化:

But sessions are implemented in Rails as session cookies, which are not persistent. I can make them persistent:

class ApplicationController < ActionController::Base
  before_filter :update_session_expiration_date

  private

  def update_session_expiration_date
    options = ActionController::Base.session_options
    unless options[:session_expires]
      options[:session_expires] = 1.year.from_now
    end
  end
end

但这似乎是一种黑客攻击,这对于这种常见功能来说是令人惊讶的。有没有更好的方法?

But that seems like a hack, which is surprising for such common functionality. Is there any better way?

编辑

Gareth的回答非常好,但我仍然希望熟悉Rails 2的人给出答案(因为它是唯一的 CookieSessionStore )。

Gareth's answer is pretty good, but I would still like an answer from someone familiar with Rails 2 (because of it's unique CookieSessionStore).

推荐答案

我花了一段时间思考这个并得出了一些结论。 Rails会话cookie默认是防篡改的,所以你真的不必担心在客户端修改cookie。

I have spent a while thinking about this and came to some conclusions. Rails session cookies are tamper-proof by default, so you really don't have to worry about a cookie being modified on the client end.

这是我的意思完成:


  • 会话cookie设置为长期(大约6个月)

  • 会话商店内


    • 设置为登录+ 24小时的过期日期

    • 用户ID

    • Authenticated = true所以我可以允许匿名用户sesssions(因为cookie篡改保护而没有危险)

    • Session cookie is set to be long-lived (6 months or so)
    • Inside the session store
      • An 'expires on' date that is set to login + 24 hours
      • user id
      • Authenticated = true so I can allow for anonymous user sesssions (not dangerous because of the cookie tamper protection)

      当用户检查记住我框,我只是将会话[:expireson]日期设置为登录+ 2周。没有人可以窃取cookie并永远登录或伪装成另一个用户,因为rails会话cookie是防篡改的。

      When the user checks the "Remember Me" box, I just set the session[:expireson] date to be login + 2 weeks. No one can steal the cookie and stay logged in forever or masquerade as another user because the rails session cookie is tamper-proof.

      这篇关于“记住我”的实施在Rails应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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