On my Github, you can download the whole sample/working solution in C# which is composed of a Xamarin.Forms project and a Back-End project in ASP.NET Core.
Resume your WebAPI call right after a token renewal.Synchronize the execution of multiple async-tasks when renewing tokens.Transparently force renewal of Access Token / JWT / Bearer Token.Execute any HttpClient call ( GET/ POST/ PUT/ DELETE) you write to consume your WebAPIs.
I’ve created a Xamarin.Forms service class called RESTService that is responsible for handling WebAPIs calls, these classes can be found in the Xamarin Forms project in the sample code available on my Github. In this scenario, you have to implement some kind of semaphore to allow only the very first async-task to perform the tokens’s renewals while the other async-tasks awaits for the renewal to finish. If you raise multiple async-task calls at the same time and your Bearer-Token expires during these calls, all of your calls would try to independently renew the token by using the Refresh-Token they have, and they will all fail. The workflow above works perfectly for single async-tasks calls. Using your existing Refresh Token to retrieve a new Bearer Token + Refresh Token pair.Īs the first option is annoying to the user, we will be covering the second one in this post today.Ī typical workflow for consuming WebApi while dealing with Bearer-Token (JWT) / Refresh Tokens renewals during calls look similar to this:.Forcing your user to re authenticate / sign-in again, or.Handling Bearer Token Renewals using Refresh Tokensįor security reasons, a Bearer Token aka JWT (JSON Web Token) does not last forever and when they expire, we must obtain a new one for being able to communicate with the back end services. Note that we are not authenticating by passing any JWT (Bearer Token) nor handling token expirations and http request retries. In the above code, we are just making an HttpClient request to a WebAPI and reading back the data. Var response = JsonConvert.DeserializeObject>(jsonResponse) ResponseMessage.EnsureSuccessStatusCode() Var responseMessage = await client.GetAsync(URL)