Best practices for managing Web API JWT token in another Web API
I will expand my comments to answer because of the characters limit.
First, re-consider / re-examine why do you need to call the auth server for every API call? Do you have a data store of some kind like a database, a cache (in memory or remote), a Azure blob storage or a shared folder? If you have, you could consider persist your access tokens to your choice of data store.
Now, let's deal with token expiration time. Depends on how the external API grants the access tokens (I assume it is OAuth2 here), you usually could access the expiration time of a token, for example using expires_in
in the response. The expires_in
is equal to seconds since the unix epoch, so you should know when the token will expire. You could then save the token granted to your data store along with their expiration time and refresh token. When you use cache, you could set the cache entry to expire minutes before the token in it expires.
When you get next API call, check if you have a "valid" token from your data store. If no, call to get new JWT token and persist it using above method. Otherwise, try make API call with the token from your data store. If you have a background service, like a WebJob or Hangfire, you could periodically validate all tokens against the token validation endpoint (if your external API provides one) and refresh them when needed.
You should always handle unauthorized responses. Tokens can be revoked before they expire. In the case of unauthorized response received at your end, you could try re-authenticate with the external API and refresh the token kept in your data store. If the token generation needs to get user involved, you could return 401 to your client.
Lastly, you will also need to consider security. When you persist the tokens, even to your own data store, you need to encrypt them. This is for ASP.NET Core, but still worth reading it and do something similar in your API.