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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "How to implement a Session Timeout in Play Framework 2"

  1. Kevin says:

    Excellent solution!

Leave a Reply


1 + seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close