reactiveui / Fusillade

An opinionated HTTP library for Mobile Development

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A message handler for authentication

promontis opened this issue · comments

Hi Paul!

I'm currently working on a project where I authenticate every api call using OAuth2/OpenId. To use this within the Fusillade stack, I've created a message handler which will do the api request, and if the request fails because the token has expired (unauthorized response), I'll post a new request to refresh the token, and re-post the original api request.

Now I would like optimize it. Currently, some of my views are making calls to my api in a concurrent way, all with a different priority. From what I see, there are at least 3 concurrent api requests at one time. Now when the token has expired, each of those concurrent api request will fail and all of them will refresh the token. I'd like only one request to refresh the token and pass its result to the other two. After the token has been refreshed, all concurrent requests should execute again.

How would you implement such a message handler?

I'd like only one request to refresh the token and pass its result to the other two

Generally the easiest way to do this is, instead of storing the Token, store the Task That Fetched The Token - this way in your code, your API methods always await taskThatIsFetchingTheToken - if the task is pending your code waits on it, but for the majority case where your task is already completed, it just immediately returns the value.

Once you see that a token is expired, you immediately Interlocked.Exchange it with a new Task that will fetch an unexpired token