Best practices for managing auth token

user_mda picture user_mda · Feb 16, 2017 · Viewed 18k times · Source

I am writing a REST client in Java using the HttpCLient , the REST API that I access needs an auth token for every REST action. This token is valid for 24 hours.

The way I am handling this now is calling a "getAuth()" method everytime I need to make a REST call which seems like an overhead on the auth server.

How can I conveniently store this auth token and manage its life cycle? Are there any documented best practices?

I thought of the following solution

public class MySession {
    String user;
    String pass;
    public MySession(String user, String pass) {
        this.user = user;
        this.pass = pass;
    }

    public getAuth() {
        //user user, pass to get auth token 
    }
}

and then pass the sessions object to any class that nees the token. If the token is expired, just call this method again

Answer

Dave L picture Dave L · Mar 1, 2017

For brevity I'll assuming you're calling an endpoint that you can't change. How you should implement will heavily depend on whether the token is app or user based (one token for all users on a shared app instance or one token per user).

If it's one auth token for the entire app:

  • Store it in memory along with a time-to-live timestamp (or alternatively catch the token expired error, request a new token and retry the original request), refresh it if it doesn't exist/is expired
  • If you're concerned about re-requesting API tokens after an application restart also store it in the database and load it at startup if it exists

If it's one token per user:

  • Store it in your user session, it's exactly what sessions are used for, if you're authing users then they'll have a session and the overhead is already there
  • If you don't want to re-request a token everytime they login store their current token in the DB and and load it into their session when they login