---
title: "How to implement a Session Timeout in Play Framework 2"
date: 2014-04-01T19:32:25+00:00
author: "poornerd"
tags: ["security"]
canonical: https://www.poornerd.com/2014/04/01/how-to-implement-a-session-timeout-in-play-framework-2/
source: Raw Markdown twin of the HTML article; content is the original source.
---
If you follow the Play Framework 2 guide for implementing authentication: <a href="http://www.playframework.com/documentation/2.2.2/JavaGuide4" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.playframework.com');" target="_blank">http://www.playframework.com/documentation/2.2.2/JavaGuide4</a> &#8211; 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 <a href="http://www.playframework.com/documentation/2.2.2/JavaGuide4" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.playframework.com');" target="_blank">guide for setting up authentication</a>, 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:

<pre class="brush: plain; title: ; notranslate" title="">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) &gt; 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();
    }
}
</pre>

Then just add a `sessionTimeout=15` (in Minutes) to your conf file.
