Search code examples
springhibernaterestspring-securityjersey

Session management for a RESTful Web Service using Jersey


I am developing a Restful Web Service using Jersey between my Android, iPhone apps and MySQL. I also use Hibernate to map the data to the database.

I have a sessionId (key). it is generated when user Login to the system.

In User class:

public Session daoCreateSession() {
    if (session == null) {
        session = new Session(this);
    } else {
        session.daoUpdate();
    }
    return session;
}

In Session Class:

Session(User user) {
    this.key = UUID.randomUUID().toString();
    this.user = user;
    this.date = new Date();
}

void daoUpdate() {
    this.key = UUID.randomUUID().toString();
    this.date = new Date();
}

When user Sign in to the system successfully, I send this sessionId to the Mobile app client. Then when I want to get some information from database based on the logged in user, I check this Session key as authentication in the REST Services for every request.

For example for the list of project that user is involved in, I use client.GET(SERVER_ADDRESS/project/get/{SessionID})

insetead of client.GET(SERVER_ADDRESS/project/get/{username}).

And if it is not a valid session key, I'll send back to the client a 403 forbidden code. You can also take a look here

The thing is I am not sure about my approach. what do you think about cons in this approach considering for Jersey and a mobile app? I still don't know if the Session key approach is a good idea in my case.


Solution

  • If you want to use SessionId then it should have a validation time, like this:

    private static final int MINUTES = 90;
    
    public boolean isValid() {
       return System.currentTimeMillis() - date.getTime() < 1000 * 60 * MINUTES;
    }