简体   繁体   中英

Play framework 2 - isAuthenticated in Java

In my action i'd like to render different views (or maybe only display some other divs) depending on whether a user is authenticated or not.

Should i do something like this:

public static Result index() {          
   if (Context.current().request().username().equals("")) {
        // user is NOT authenticated
        return ok(welcome.render());
    } else {
        // user is authenticated
        return ok(dashboard.render());
    }
}

And how about checking if a user is authenticated in a view? I know I can use the @Security.Authenticated(Secured.class) annotation, but how do things conditional?

Depends on what you're trying to achieve. If you only need to decide whether a user is logged in or not, you can use something like you wrote, in your controller classes, eg:

public static boolean loggedIn() {
        return (session().get("userId") != null);
    }

then in the static controller methods check whether the user is logged in:

if (!loggedIn()) {
            return redirect(routes.Application.login());
        }

Notice the use of the session() by which you can access the secure session cookie's map, and from there you can get the user id. If you want to implement more complex logic, eg. different actions for different user groups, then it's a different story.

Either use some maps in a cache with the authenticated user id-s and you validate the userId in the session, whether it's in the map, or alternatively you can use some property of the user (eg. a set of userRoles) and set what is visible accordingly. These are the most sensible ways I'm aware of.

(here's how you can use the session() of controller: Controller , Session )

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