0

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?

1 Answers1

1

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
AndrewR
  • 1,252
  • 8
  • 7
  • Thank you for your reply. I think this is my best bet. Do you know how to accomplish synchronization of threads in C#? Is it just using "lock"? Like you said if 10 requests come in at the exact same time and there is no token available (I guess I'll need to store that somewhere, in a database?) then I only want one of the requests to get the token and the other 9 be able to also use that same token. – StealthGhost Nov 03 '22 at 15:40
  • 1
    I don't code in C# (I am a java person), but a quick search tells me to use locks; something like https://stackoverflow.com/questions/15027522/synchronized-methods-in-c-sharp – AndrewR Nov 03 '22 at 20:12