rails/devise 如何处理 cookie 会话? [英] How does rails/devise handle cookie sessions?

查看:20
本文介绍了rails/devise 如何处理 cookie 会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解在使用 rails/devise 登录用户时到底发生了什么.

I'd like to understand what's really going on when signing in a user with rails/devise.

我创建了一个最小的 rails 应用程序,安装了设计并创建了一个 User 设计模型.一切正常,当我登录时(使用 remember me),我按预期获得了一个会话 cookie.

I've created a minimal rails app, installed devise and created a User devise model. Everything works fine, and when I log in (using remember me) I get a session cookie just as expected.

现在困扰我的是:rails 如何处理浏览器通过 cookie 传递的会话信息?

Now what's bugging me is : How does rails handle the session informations that the browser is passing through the cookie ?

我天真地希望一些信息存储在数据库中,但我没有看到在哪里.没有 session 表,Users 中没有 session 列,我在 tmp 目录中找不到任何感兴趣的东西.

I'd naively expect some information to be stored in the database, but I don't see where. There's no such thing as session table, no session column in Users, and I couldn't find anything of interest in the tmp dir.

请注意,重新启动服务器不会终止我的会话.这当然是意料之中的,但现在我真的很想知道这里发生了什么样的魔法?

Note that restarting the server wouldn't kill my session. It is of course expected, but now I'm really wondering what kind of magic is happening here ?

换句话说:服务器如何检查 cookie 的有效性来验证用户身份?

in other words : how does the server check the validity of a cookie to authenticate a user ?

谢谢!

推荐答案

默认的 Rails 会话存储是 CookieStore.这意味着所有会话数据都存储在 cookie 中,而不是存储在数据库中的任何地方.在 Rails 3.2 中,cookie 被签名以防止篡改,但没有加密.在 Rails 4 中,它通常默认加密.它在 cookie 中的事实是它如何在您的服务器重新启动后持续存在.这也意味着您只能存储 4k 的数据,并且您不想在 Rails < 中存储任何敏感的数据.4. 无论如何,最好在会话中保留最少的数据.

The default rails session storage is CookieStore. This means that all the session data is stored in a cookie rather than in the database anywhere. In Rails 3.2 the cookie is signed to prevent tampering, but not encrypted. In Rails 4 it's generally encrypted by default. The fact that it's in a cookie is how it persists across restarts of your server. It also means you can only store 4k of data and you wouldn't want to store anything sensitive in there in Rails < 4. It's best to keep a minimum of data in the session anyway.

您还可以选择将会话数据存储在数据库中,并且只在 cookie 中包含会话 ID.

You can also opt for storing the session data in the database and only having a session id in a cookie.

我前一周给出的这个答案包含一些可能有用的额外信息:

This answer I gave the other week has some extra info that might be useful:

会话在我开始在线阅读它们之前对我来说很有意义

此外,CookieStore 的 rails api 文档提供了一个很好的总结:

Also, the rails api doc for CookieStore gives a nice summary:

http://api.rubyonrails.org/classes/ActionDispatch/Session/CookieStore.html

这篇关于rails/devise 如何处理 cookie 会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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