I am using Auth0, which gives me a JWT (json web token) and a refreshtoken. I use this JWT in the http headers to communicate with my backend.
It could happen, that the server gives me a 403
, when it decides that the JWT has expired. In this event, I can ask Auth0 to issue me a new JWT, using the refreshtoken. It means I call the Auth0 backend, pass it the refreshtoken, and it gives me a new JWT, which I can then use in my requests.
My question is, how can I efficiently write this behaviour in all my networking code? I will have a couple of endpoints to talk to, and they all might return the 403.
I am thinking I should first make an interceptor that adds the JWT to all requests.
Then there should be behaviour that detects the 403, quietly does a networkcall to Auth0, retrieving the new JWT. Then the original request should be tried again, with the new JWT in its headers.
So I would prefer to have this 403 handling somewhere invisible to my other code, and definitely not have to rewrite it everywhere.
Any pointers on how to achieve this will be appreciated.
--
To be clear, I am basically looking for pointers on how to achieve this using RxAndroid Observables. When a certain Observable finds the 403, it should 'inject' a new network call.
Instead of refreshing tokens only after receiving a 403 response, you could check the expiration time locally and refresh accordingly by checking the token's
exp
claim. For example, this example uses the same approach in Angular. It's not specific to Android, but the idea is the same:I solved this issue by writing an
Interceptor
forOkHttp
. It checks the statuscode of the network call. If it's a 403, call Auth0 servers and request a new id_token. Then use this token in a new version of the original request.To test, I wrote a little webserver that checks the TestHeader for fail or succeed and returns a 403 if it's fail.
Then I attach this Interceptor to an OkHttpClient which I plug into the Retrofit adapter: