If you follow the Play Framework 2 guide for implementing authentication: http://www.playframework.com/documentation/2.2.2/JavaGuide4 — 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 guide for setting up authentication, 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:
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 Minutes) to your conf file.
| Reference: | How to implement a Session Timeout in Play Framework 2 from our JCG partner Brian Porter at the Poornerd blog. |
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Thank you!
We will contact you soon.
Tags
Play Framework
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Excellent solution!
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!