Enterprise Java

How to implement a Session Timeout in Play Framework 2

If you fol­low the Play Frame­work 2 guide for imple­ment­ing authen­ti­ca­tion: http://​www​.playframe​work​.com/​d​o​c​u​m​e​n​t​a​t​i​o​n​/​2​.​2​.​2​/​J​a​v​a​G​u​i​de4 — you will notice that there is no ses­sion time­out in Play Frame­work 2. It was there in Play Frame­work 1, but Play Frame­work 2 fol­lows a dif­fer­ent approach.

I you want to imple­ment your own ses­sion time­out, then fol­low the guide for set­ting up authen­ti­ca­tion, by extend­ing the Security.Authenticator, and store a time­stamp in the ses­sion and keep extend­ing 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 Min­utes) to your conf file.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kevin
Kevin
9 years ago

Excellent solution!

Taryono
9 years ago

Hi Brian Porter….I just want to ask..how to implement this sessionTimeOut if user has in idle for one hour…session time will reset to one hour if user do action, if user in idle more than one hour session timeout working…please help me!

Back to top button