简体   繁体   中英

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. The Appication controller has an authenticate method , and during that method the User.authenticate method is called. 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. 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. I don't want to requery the database, I'd like to use the same User object that was just found in Login.validate . 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.

http://www.playframework.org/documentation/api/2.0.4/java/play/mvc/Http.Session.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM