Sunday, September 7, 2014

Implementing session timeout in playframework

According to play documentation "There is no technical timeout for the Session. It expires when the user closes the web browser. If you need a functional timeout for a specific application, just store a timestamp into the user Session and use it however your application needs (e.g. for a maximum session duration, maximum inactivity duration, etc.)."

So I used the following way to implement a session timeout. Following custom authenticator class was used to implement this.

  public class ValidateUserSessionAction extends Security.Authenticator{

    public String getUsername(Http.Context ctx) {
        long currentTime=System.currentTimeMillis();
        long timeOut=Long.parseLong(Play.application().configuration().getString("sessionTimeout")) * 1000 * 60;
        String temp=ctx.session().get(Constants.LAST_SEEN_KEY);
        if (temp == null) {
            temp = String.valueOf(currentTime);
        if((currentTime-Long.parseLong(temp))<timeOut) {
            //If multiple instances are running, time should be synchronized between nodes
            ctx.session().put(Constants.LAST_SEEN_KEY, String.valueOf(System.currentTimeMillis()));
            return ctx.session().get(Constants.SESSION_USER_KEY);
            return null;

    public Result onUnauthorized(Http.Context ctx) {
        return redirect(controllers.routes.UserController.signIn());


Above authenticator class can be used to validate user actions like below.
    public static F.Promise<result< updateEmail() {
        //do something
        return ok();

No comments:

Post a Comment