Вопрос

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.

Это было полезно?

Решение

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).

Другие советы

Session timeouts

  • The session timeout configuration item, session.maxAge, used to be an integer, defined to be in seconds. Now it’s a duration, so can be specified with values like 1h or 30m. Unfortunately, the default unit if specified with no time unit is milliseconds, which means a config value of 3600 was previously treated as one hour, but is now treated as 3.6 seconds. You will need to update your configuration to add a time unit.

See here

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top