0

Is there a pattern for how should I store and reuse a restAPI authorisation token across multiple classes?

I'm consuming a RestAPI, my login code takes a user, password and server and then returns an auth token. That login code sits in a common base class for all my RestAPI calls which works fine. But each new object doesn't know the token so has to reauthorise. I need them to share the same token once it's been generated. I can't use a singleton as I may have to login with multiple different users in the same session.

I'm sure there's a pattern for that but I can't find it, can you help?

MrTelly
  • 14,657
  • 1
  • 48
  • 81

1 Answers1

0

What you need is a cache. The login service can be a singleton that cache access tokens, you can use a concurrent dictionary to implement the access tokens cache.

Something like this:

public class LoginService
{

    private ConcurrentDictionary<string, string> accessTokenCache = new ConcurrentDictionary<string, string>();

    private string callServerLogin(string user, string password)
    {
        throw new NotImplementedException();
    }

    public string Login(string user, string password)
    {
        var accessToken = callServerLogin(user, password);
        accessTokenCache[user] = accessToken;
        return accessToken;
    }

    public bool TryGetCachedAccessToken(string user, out string accessToken )
    {
        return this.accessTokenCache.TryGetValue(user, out accessToken);
    }

}
Jesús López
  • 8,338
  • 7
  • 40
  • 66