I have an ASP.NET web application that presents data retrieved from a web service.
Before getting actual data from the service a token must be retrieved by calling a specific method in that service. This token must then be providing in any subsequent data method calls. This token expires after some time and a call to a data method with an expired token leads to an error and a new token must be retrieved for further communication. The active token is kept in a global ASP.NET application variable.
This is all fine, but how do I prevent overlapping token renewals? A request from one user to the site triggers a service call, this gives an error and a new token is retrieved and put in the cache, but in the meantime another user request finds that the token is expired and also renews the token.
Is there not a problem here? I can’t really wrap my head around it.
You can do so by locking (Expiration = 2 hours):
Having a global token like this might not be best practice though.
Also this code blocks all other token requests while the token is being regenerated, depending on how long the token generation takes this might not be acceptable.