How to implement a Session Timeout in Play Framework 2


If you follow the Play Framework 2 guide for implementing authentication: http://www.playframework.com/documentation/2.2.2/JavaGuide4
– you will notice that there is no session timeout in Play Framework 2.
It was there in Play Framework 1, but Play Framework 2 follows a
different approach.
I you want to implement your own session timeout, then follow the guide for setting up authentication, by extending the Security.Authenticator, and store a timestamp in the session and keep extending it every time a request is made.
Here is how I did it:

public class Secured extends Security.Authenticator {
    public static final String UNAUTHENTICATED = "unauthenticated";
    public static User getLoggedInUser() {
        if (session("userId") == null)
            return null;
        return User.findById(Long.parseLong(session("userId")));
    }
    public static String getLoggedInUsername() {
        if (session("userId") == null)
            return null;
        return User.findById(Long.parseLong(session("userId"))).getUsername();
    }
    @Override
    public String getUsername(Http.Context ctx) {
        // see if user is logged in
        if (session("userId") == null)
            return null;
        // see if the session is expired
        String previousTick = session("userTime");
        if (previousTick != null && !previousTick.equals("")) {
            long previousT = Long.valueOf(previousTick);
            long currentT = new Date().getTime();
            long timeout = Long.valueOf(Play.application().configuration().getString("sessionTimeout")) * 1000 * 60;
            if ((currentT - previousT) > timeout) {
                // session expired
                session().clear();
                return null;
            }
        }
        // update time in session
        String tickString = Long.toString(new Date().getTime());
        session("userTime", tickString);
        return User.findById(Long.parseLong(session("userId"))).getUsername();
    }
}

Then just add a sessionTimeout=15 (in Minutes) to your conf file.

Leave a Reply

Your email address will not be published. Required fields are marked *