Java Play! 2 - User management with cookies

2020-02-09 05:48发布

问题:

I am trying to manage my user via cookie. It's not that easy because there is absolutely no documentation about this topic.

With the help of the sample "zentask" I made this:

session("username", filledForm.field("username").value());

public class Secured{

    public static Session getSession() {
        return Context.current().session();
    }

    public static String getUsername() {
        return getSession().get("username");
    }

    public static boolean isAuthorized() throws Exception {
        String username = getUsername();
        if (username == null)
            return false;
        long userCount = DatabaseConnect.getInstance().getDatastore()
                .createQuery(User.class).field("username").equal(username)
                .countAll();

        if (userCount == 1)
            return true;

        return false;

    }

I am using it like this:

public static Result blank() throws Exception {

        if (Secured.isAuthorized())
            return ok(Secured.getUsername());
        else
            return ok(views.html.login.form.render(loginForm));

    }

Now I have several questions/problems:

  • 1.) Cookie is not dectypted and always looks the same. eg bdb7f592f9d54837995f816498c0474031d44c1a-username%3Akantaki

  • 2.) What does the class Security.Authenticator do?

  • 3.) I think user management through cookies is a very common problem, does play!2.0 offer me a complete solution? Or is there at least some documentation?

回答1:

There is also full stack for authentication and authorization - Play Authenticate by Joscha Feth. (available at GitHub)

It incorporates ready-to-use sample for Java, which uses concepts of securesocial + full Deadbolt 2 (by Steve Chaloner) support. it has:

  • built in possibility to register and log in users with e-mail, Google, Facebook, Foursquare, Twitter, OpenId and custom providers.
  • Multilanguage support (currently: English, German, Polish)
  • Customisable templates (also for informational e-mails)
  • Support for roles and permissions (via Deadbolt 2)
  • Password recovery support

There is sample app for Java in it. You can incorporate it to your app.



回答2:

As shown in the Zentask sample, your Secured class should extend Security.Authenticator.

With this, it will allow to put a @Security.Authenticated annotation either on a Controller, or on an Action. This annotation allows to redirect the client to another page if the user is not properly authorized (by overriding the Security.Authenticator.onUnauthorized() method).

The workflow is the following:

  1. Check authorization:
  2. Add an unique identifier in the client cookies
  3. Check if authenticated
  4. Secure a controller or an action
  5. If not authorized, redirect the client to another page