Reputation: 2733
I want to know if the user's session has expired in the server side and perform something when that happens. How do I do this?
I'm using Java and Play framework 2.2.1.
Upvotes: 9
Views: 8141
Reputation: 553
Session timeouts
Upvotes: 0
Reputation: 22355
When using Play's built-in authentication, at every authenticated request, store a timestamp in the session with the updated expiration.
Then, in the authenticator, validate the session expiration.
The article How to implement a Session Timeout in Play Framework 2 offers this example:
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();
}
}
This requires a sessionTimeout
value in minutes in the application's configuration file (application.conf
).
Upvotes: 11