Play Framework Basic Auth User Not Changing Between Sessions

315 views Asked by At

I'm trying to implement Basic Auth with the play framework.

public class BasicAuth extends Action.Simple {

    private static final String REALM = "Authorisation Needed";
    private static final String AUTHORISATION = "authorization";
    private static final String WWW_AUTHENTICATE = "WWW-Authenticate";

    private static final F.Promise<Result> UNAUTHORISED = F.Promise.pure((Result) unauthorized());

    @Override
    public F.Promise<Result> call(Http.Context context) throws Throwable {
        Optional<String> auth_header = Optional.ofNullable(context.request().getHeader(AUTHORISATION));

        if (!auth_header.isPresent()) {
            context.response().setHeader(WWW_AUTHENTICATE, REALM);
            return UNAUTHORISED;
        }

        String encoded_credentials = auth_header.get().substring(6);
        byte[] decoded_credentials = Base64.getDecoder().decode(encoded_credentials);
        String[] credentials = new String(decoded_credentials, "UTF-8").split(":");

        if (credentials == null || credentials.length != 2) {
            return UNAUTHORISED;
        }

        User user = authorise(credentials);

        if (user == null) {
            return UNAUTHORISED;
        }

        context.session().put("email", user.getEmail());

        return delegate.call(context);
    }

    private User authorise(String[] credentials) {
        String username = credentials[0];
        String password = credentials[1];
        return User.find.where().eq("email", username).eq("password", password).findUnique();
    }

}

But the user doesn't change between requests. I.e. I log in with Joe Bloggs after initialising the server and it returns Joe as the current user.

Next request I log in with Bill Gates, and it returns Joe Bloggs as the current user.

I am returning the email stored in the session in the controller as so:

User logged_user = UserDao.findByEmail(context.session().get("email"));

I really need to fix this. Any help please?

0

There are 0 answers