Search code examples
c#oauth-2.0oauthtokenbearer-token

How do I make sure to only create one OAuth 2.0 token at a time?


I have multiple processes (some that are not under my control) that need to access an API that only allows me to create one OAuth 2.0 token at a time. If I create additional tokens, I run the risk of kicking users out of the application. What would you suggest on how to manage this?

I am thinking I will need to create a middle layer to manage the token and pass through the information to the API. This is fine, but even so, how do I make sure that I only ever have one active token at a time if there are multiple requests coming in per second to this middle layer? Would I not run the risk of one call creating a token because none exists (so it cannot be refreshed) at the same time another call is performing the same action?


Solution

  • Given the fact that there are multiple processes, the oauth endpoint is the spot where all of them meet. Seems like a logical spot to address the issue.

    First of all, I would create an oAuth proxy (as you said), so all of processes use that to get access/refresh token. This proxy will be used for both getting original access/refresh tokens and handling refresh as well.

    As for making access token being exactly one thing, I would use this logic:

    • initially, the proxy has no access token, so when multiple processes come to get one, the proxy will hold all of those threads and will request exactly one access/refresh tokens from the original oAuth server
    • since you control the proxy, you can synchronize threads to make sure they all wait for the access token to be available
    • at this point every process will have the same access token
    • I would make the proxy to understand when the access token get expired, so when a process asks for a token, and if the token is expired (but not before) then the proxy would refresh the token, cache it and return
    • the fact that the proxy won't request a new token till the old one expires; that guarantees that there will be no more than one access token available at the same time