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{
@Override
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);
}else{
ctx.session().clear();
return null;
}
}
@Override
public Result onUnauthorized(Http.Context ctx) {
return redirect(controllers.routes.UserController.signIn());
}
}
Above authenticator class can be used to validate user actions like below.
@Security.Authenticated(ValidateUserSessionAction.class)
public static F.Promise<result< updateEmail() {
//do something
return ok();
}
Comments
Post a Comment