I have an application (A) where multiple users can login via. username and password and receive a token for upcomning requests. If their token expires they can get a new one. This all works fine. Now the problem is that sometimes App (A) needs to access App (B) via. an API-call that also in itself requires a (separate) token. The call(s) from A to B needs to use the same token regardless of which client makes the call. In other words - app B does not need to know which client makes a call, it just sees every call as coming for app A.
My issue here comes with generating and refreshing TokenB in a threadsafe manner. Let's say TokenB has expired and C1,C2,C3 all makes a call at exactly the same time. Of course only one new token should be generated.
I figure this is a quite common obstacle, but I can't really find any guides on this specific topic of thread-safe token (re)generation.
App A is written in C# btw. Not that it matters for the issue, but perhaps Microsoft has a solution for this.
Good question and it is tricky to deal with token refresh in OAuth clients. There are two common techniques. I prefer the second of these since it is more reliable, but it requires trickier code:
SYNCHRONIZING TOKEN REFRESH
A common technique can be to make the client code look simple from the outside:
var data = await myApiClient.getData();
But somewhere in the implementation you use a collection of callbacks when a token refresh is necessary. The first of these makes the actual refresh call, and when it completes it resolves all other callbacks with the same result.
EXAMPLE CODE
Here is some TypeScript code that handles concurrent in-flight token refresh. In C# you could do an equivalent thing with tasks, and your callback handling would need to be thread safe: