java 如何在 Play Framework 中存储 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5011201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I store a cookie in Play Framework?
提问by sanity
I want to store an authentication token with Play Framework that outlives the current session, perhaps for days or even weeks - so that users don't have to login every time.
我想使用 Play Framework 存储一个比当前会话寿命更长的身份验证令牌,可能会持续数天甚至数周 - 这样用户就不必每次都登录。
What is the recommended way to do this?
推荐的方法是什么?
回答by Codemwnci
The response object has a method setCookie, which does exactly what you want
响应对象有一个方法 setCookie,它完全符合你的要求
response.setCookie("playlonglivecookie", yourData, "14d");
Remember, that the data stored in the cookie is not encrypted, so if you want to encrypt it, then use the Crypto.sign
method. Which signs your code using the play framework secret key.
请记住,存储在 cookie 中的数据未加密,因此如果您想对其进行加密,请使用该Crypto.sign
方法。它使用播放框架密钥对您的代码进行签名。
回答by mandubian
I would also advise you to have a look at the secure module provided in play-1.x/modules/secure and the file Secure.java... it provides a checkbox "remember me" in the login form which allows keeping you logged for eternity.
我还建议您查看 play-1.x/modules/secure 中提供的安全模块和文件 Secure.java...它在登录表单中提供了一个复选框“记住我”,允许您保持登录状态永恒。
and the code of this function (specially the response.setCookie at the end):
以及这个函数的代码(特别是最后的 response.setCookie):
public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
// Check tokens
Boolean allowed = false;
try {
// This is the deprecated method name
allowed = (Boolean)Security.invoke("authentify", username, password);
} catch (UnsupportedOperationException e ) {
// This is the official method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
}
if(validation.hasErrors() || !allowed) {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}
// Mark user as connected
session.put("username", username);
// Remember if needed
if(remember) {
response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
}
// Redirect to the original URL (or /)
redirectToOriginalURL();
}
Pascal
帕斯卡
回答by db80
With play > 2.5 setCookieis deprecated.
不推荐使用 play > 2.5 setCookie。
you can use instead:
你可以使用:
Http.Response.setCookie(Http.Cookie cookie)
You can create a new cookie with the builder:
您可以使用构建器创建一个新的 cookie:
Http.Cookie.builder("name", "value").withMaxAge(15).build();
15 days is the expiration date
15天是有效期
参考:https: //www.playframework.com/documentation/2.5.x/api/java/play/mvc/Http.Response.html#setCookie-play.mvc.Http.Cookie-
示例:https: //github.com/playframework/playframework/blob/master/framework/src/play/src/test/java/play/mvc/CookieBuilderTest.java