[英]In Play 2 framework (Java), how to add User object to session after authentication
I looked at the "zentasks" sample code to learn some basic user login and security stuff. 我查看了“ zentasks”示例代码,以了解一些基本的用户登录和安全性知识。 The Appication controller has an authenticate method , and during that method the User.authenticate method is called.
Appication控制器具有一个authenticate方法 ,在该方法期间,将调用User.authenticate方法 。 Here are a couple code snippets from those links:
以下是这些链接中的几个代码段:
public static Result authenticate() {
Form<Login> loginForm = form(Login.class).bindFromRequest();
if(loginForm.hasErrors()) {
return badRequest(login.render(loginForm));
} else {
session("email", loginForm.get().email);
return redirect(
routes.Projects.index()
);
}
}
...
public static class Login {
public String email;
public String password;
public String validate() {
if(User.authenticate(email, password) == null) {
return "Invalid user or password";
}
return null;
}
}
As you can see, if it authenticates (ie, finds a User object), the authenticate
method adds "email" to the session. 如您所见,如果它进行身份验证(即找到一个User对象),则
authenticate
方法将“ email”添加到会话中。 I'd like to add the full user object instead, but in the controller action, where I have the session, I don't have the User
object. 我想改为添加完整的用户对象,但是在执行会话的控制器操作中,没有
User
对象。 I don't want to requery the database, I'd like to use the same User
object that was just found in Login.validate
. 我不想重新查询数据库,我想使用在
Login.validate
找到的同一User
对象。 What's a good way to do that? 有什么好方法吗?
Is there a reason you can't simply add a field to your login class? 您是否有理由不能简单地在登录类中添加字段?
public static class Login {
public String email;
public String password;
public User user;
public String validate() {
user = User.authenticate(email, password);
if(user == null) {
return "Invalid user or password";
}
return null;
}
}
Not that this will necessarily help you, looking at the API it seems you can't add an object to the session, only Strings. 并非一定会对您有帮助,但查看API似乎您无法将对象(仅字符串)添加到会话中。
http://www.playframework.org/documentation/api/2.0.4/java/play/mvc/Http.Session.html http://www.playframework.org/documentation/api/2.0.4/java/play/mvc/Http.Session.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.