如果您遵循Play Framework 2指南以实施身份验证: http://www.playframework.com/doc-m-e-t-t-i o / n..2..2..2 / Jac agéide4-您会注意到Play框架2中没有会话超时。在Play框架1中存在,但Play框架2采用了不同的方法。
我要实现自己的会话超时,然后通过扩展Security.Authenticator
遵循设置身份验证的指南 ,并在会话中存储时间戳,并在每次发出请求时继续扩展它。
这是我的做法:
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();}@Overridepublic String getUsername(Http.Context ctx) {// see if user is logged inif (session("userId") == null)return null;// see if the session is expiredString 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 expiredsession().clear();return null;}}// update time in sessionString tickString = Long.toString(new Date().getTime());session("userTime", tickString);return User.findById(Long.parseLong(session("userId"))).getUsername();}
}
然后只需将sessionTimeout=15
(以分钟为单位)添加到您的conf文件中。
翻译自: https://www.javacodegeeks.com/2014/04/how-to-implement-a-session-timeout-in-play-framework-2.html