Where to handle getting new access token with refresh token using Refit and Xamarin Forms

Viewed 386

I am currently using Refit and have been handling my auth stuff in an AuthenticationService where I set my Refit settings to have AuthorizationHeaderValueGetter use my AuthenticationService.GetAuthenticationToken() to get my access_token. The logic inside my GetAuthenticationToken() method checks the token expiration and will attempt to use the refresh_token to get a new access_token if it is expired. If all fails it will show the login screen of my app.

My test group has reported that they are asked to login frequently so I feel like there is something not working optimally in my design.

Am I doing too much in the AuthorizationHeaderValueGetter?

Should I be doing this in a DelegatingHandler where I can resubmit the api request after getting a new access_token?

I have background fetch stuff that happens in my app so I need to be able to have the refresh_token automatically get a new access_token during the background process.

1 Answers

Ok, so I stumbled upon my issue. The sequence that created this problem in the wild is:

  • app is backgrounded after user is logged in and using app normally
  • the access_token expires while in the background
  • background fetch runs getting a new access_token and refresh_token and doing normal work
  • user foregrounds the app

The problem was that the new token info was not persisted when the background fetch ran. So, when the user foregrounded the app my ResumeManager checked IsUserLoggedIn which used the old token info, so it would see an expired access_token and tried to use an already consumed refresh_token since it was used in the background fetch. This resulted in an invalid_grant and the login screen was displayed.

The good news is, easy fix and my logic is fine, also it appears doing all this in the AuthorizationHeaderValueGetter is not a problem.

Hopefully this info helps someone else even though it was more a careless mistake than anything else.

Related