title: How can I avoid this token refresh concurrency issue in ICookieAuthenticationProvider.ValidateIdentity?
body: <p>I've given the owin pipeline my own CookieAuthenticationProvider with </p>
  
  <pre><code>public async override Task ValidateIdentity(CookieValidateIdentityContext context)
  </code></pre>
  
  <p>In this method I check a 3rd party token in the claims of the users identity to see if it's expired or close to expiring. If so I use it's refresh token to obtain a new access token from the 3rd party, generate a new identity with the new access and refresh tokens, then sign in and replace the current identity. This way the user always has a valid access token to the 3rd party site.</p>
  
  <p>This works pretty flawlessly except we have a lot of ajax requests as well as some signalr real time requests coming in. So very commonly 2 requests from a user will be processing on different threads A &amp; B. Thread A hits the [Authorize] attribute first which fires off the Validate-identity. It sees the token will or has expired and calls for a refresh. Meanwhile Thread B ends up doing the same thing. Thread A finishes first and now has a new access token and refresh token, Thread B fails to refresh because it called for the refresh using the original refresh token which the 3rd party now considers invalid and denies any new access token so the users request becomes unauthorized. Thread A finishes and everything looks good. Thread B fails whatever it was going to do in the first place.</p>
  
  <p>My question is, is this the right place to do this? Is there a better way? How can I avoid this race condition?</p>