【问题标题】:How do I handle a session timeout or expiration in Play Framework?如何在 Play Framework 中处理会话超时或到期?
【发布时间】:2014-04-25 02:59:21
【问题描述】:

我想知道用户的会话是否在服务器端过期,并在发生这种情况时执行某些操作。我该怎么做?

我正在使用 Java 和 Play 框架 2.2.1。

【问题讨论】:

标签: java playframework playframework-2.0 playframework-2.2


【解决方案1】:

使用 Play 的 built-in authentication 时,在每个经过身份验证的请求中,在会话中存储一个时间戳,并更新过期时间。

然后,在身份验证器中,验证会话到期。

文章How to implement a Session Timeout in Play Framework 2提供了这个例子:

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();
    }
}

这需要在应用程序的配置文件 (application.conf) 中以分钟为单位的 sessionTimeout 值。

【讨论】:

  • 抱歉回复晚了,我会尽快回复这个,看看是否有效。非常感谢。
  • 我建议在getUsername的正文中使用ctx.session().replace("userTime", tickString);
  • session(String) 在什么包中?
  • 通过ctx对象访问session(String)...ctx.session(String)
  • 我们需要设置session("userTime")吗?
【解决方案2】:

会话超时

  • 会话超时配置项session.maxAge,以前是整数,定义为秒。现在它是一个持续时间,因此可以使用 1h 或 30m 等值指定。不幸的是,如果没有指定时间单位,则默认单位是毫秒,这意味着配置值 3600 以前被视为一小时,但现在被视为 3.6 秒。您需要更新配置以添加时间单位。

See here

【讨论】:

    猜你喜欢
    • 2017-09-03
    • 2018-10-14
    • 2018-01-24
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 2017-10-06
    • 2012-08-16
    • 1970-01-01
    相关资源
    最近更新 更多