创建会话和cookie之间的区别? [英] Difference between creating a session and a cookie?

查看:218
本文介绍了创建会话和cookie之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Play的第一个网站上工作!框架,一旦我在用户登录时调用此方法:

I'm working on my first website with the Play! framework, and at one point I'm calling this method when the user logs in:

static void connect(User user){
    session.put("userid", user.id);
}

只需将用户ID存储在会话中,每个请求,工作正常。问题是,一旦浏览器关闭cookie失去了,用户需要重新登录。我想创建一个记住我选项,似乎唯一的方法是创建一个cookie,并发送它与响应,如下:

Simply storing the userid in a session, and I can check if it's set on each request, works fine. Problem is, once the browser is closed the cookie is lost, and the user needs to login again. I want to create a "remember me" option, and it seems that the only way to do that is create a cookie and send it with the respons, like this:

response.setCookie("user", userdata, "14d");

所以我想知道,创建会话的关键是什么, ? (但不给我任何控制的cookie时间)。还有一件事我还没有找到,是如何从请求中读取cookie?

So I'm wondering, what's the point in creating a session, when it does the exact same thing? (But does not give me any control over the cookie time). And another thing I havn't found yet, is how to read the cookie from the request?

(我知道的事实,使用setCookie创建的cookie未加密,我需要调用 Crypto.sign()

(And I'm aware of the fact that cookies created with setCookie are not encrypted and I need to call Crypto.sign())

推荐答案

1)在Play的会话!

1) A Session in Play! is always maintained via cookie (i.e in client side), this is attributed to 'Share nothing' approach.

2)如果您使用安全模块(或者您可以使用安全模块)看看代码,如果你正在编写你自己的),'authenticate()'方法接受参数'记住'并设置会话30天( response.setCookie(rememberme,Crypto .sign(username)+ - + username,30d);

2) If you use Secure module (or you can take a look at the code and follow if you are writing your own), the 'authenticate()' method takes the parameter 'remember' and set the session for 30 days (response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");)

如果用户没有选择记住,他们的会话只会持续到浏览器关闭。

ie. if user doesn't choose to be 'remembered', their session last only until the browser is closed.

3)真正的区别是,正如你所说,session。 put()不允许设置会话超时时间。

3) The real difference is, as you mentioned, session.put() doesn't allow to set session time out. If you want to extend the session then set it on the cookie.

4)如果您想在用户执行CRUD时进行额外的身份验证,即使用户选择记住 '或他们的会话被你显式扩展)更好地设置用户名/ ID缓存(而不是设置另一个标识符到会话),并清除它,当用户注销。

4) If you want additional authentication while user performing CRUD, (even if user choose to be 'remembered' or their session got extended explicitly by you) its better to set the username/id to cache (rather than setting another identifier to session again) and clear it off when user logout. This will scale well if you choose to use a distributed cache like memcache.

5)要从cookie读取, request.cookies.get(名称)很方便。

5) To read from cookie, request.cookies.get("name") comes handy.

这篇关于创建会话和cookie之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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