I have a problem with auth flow in my app. There is some API that I use for authorisation (how it works: I am sending request and it sets auth token cookies in HTTPCookieStorage.shared with some expire time (20 min)). If user is authenticated, I have authToken cookie in HTTPCookieStorage.shared, if not, HTTPCookieStorage.shared is empty.
Now I faced problem, how to refresh expired token. For example, if I don't use app for a hour, my token is expired and I can't use other api calls before getting new authToken.
For now I have following solution: I call auth request before every request and check if I have something in HTTPCookieStorage.shared If yes, then I return .just(my_auth_token), If no, I getting new token, by triggering request for auth.
But it have one huge flaw: if I have more than one request at app startup, there will be more than one auth request that can lead to unexpected behaviour of the auth token (like it can be immediately expired, because we already get new token from another auth request)
So question is: How to make other observables wait until there will be some authToken? I was thinking about skipUntil operator, but I think its not suitable either, because once it triggered, it pass all events, what came into observable. Its bad because once we refresh token, we can't refresh it second time.
Here is an article I wrote that solves this problem: RxSwift and Handling Invalid Tokens
The "huge flaw" you mentioned is one of the use cases I accounted for:
The solution...
Once you have a properly constructed TokenAcquisitionService object, you will be able to handle requests as follows:
The
TokenAcquisionServiceI built is provided in the article along with an analysis of how it works and a full test harness proving it works. It has been used in several projects that I know of.