Group Group Group Group Group Group Group Group Group

Auto refresh token


Hi guys!
I want to ask a question: on every remote API perform when 2 more API return error (token expired, invalid …), I want to have service that will renew token then continues APIs that performs error before without logout app.

Thank you, guys!
sorry for my English!


Hi @xuanchinh1988!

:+1:, this is a tricky one to solve. I’ve implemented this several different ways in the past. Here’s the simplest approach that I think works well:

  • RemoteUserSession: Design the remote user session as a reference type, i.e. using a class. Because multiple remote API objects could be reading the token from multiple threads, make sure to make the token thread safe when reading/writing.
  • Remote API: Have your remote API objects hold on to the RemoteUserSession via a stored property.
  • On HTTP auth error: When a request fails because of a bad token, have the remote API object ask the auth remote API to refresh the token. This is one of the trickiest parts… you could inject every remote API with the auth remote API, that’s the easiest way. This gives every remote API direct access to the auth remote API. You could also take more loosely coupled approach using notification center notifications or through a redux state store.
  • Refreshing the token: The auth remote API also has access to the user session reference, so when the auth remote API gets a new token from the server, it can mutate the token stored in the remote user session object. Because it’s a reference type, all other remote APIs will now read the new token. Watch out for concurrency issues here.
  • On token refreshed: The remote API that failed will probably want to know when the token finishes refreshing so that it can retry the request. If the remote API has direct access to the auth remote API you could add a completion closure to the refreshToken() method. You could also use notifications to signal the result of the token refresh.

One neat advanced strategy you could use here is to use some sort of GCD queue for making the token thread safe to read and write. While the auth remote API is refreshing the token with the server, you could pause the reading queue, effectively blocking all readers of the token while it gets refreshed. Just make sure no object is trying to read the token from the main thread.

Hope this helps. Please let me know if I wasn’t clear on anything or if you have any other questions. Also, we are currently evaluating what to add in the book’s next update. Please let us know if this is something you’d like us to cover in the next version of the book.