Problem Solved 2: Access Token refresh with Okhttp Authenticator


Android Perspective: If your backend is supporting OAuth, then your Access-token will be JWT (Json Web Token), which backend must send you on successful login to use your resource. Now you can check the validity of this JWT a.k.a Access-token by putting this whole key string here. You will get a lot of details out of it, but the most interesting thing is expiry date. It is after this expiry date, the JWT will not be valid anymore. So if you call your endpoint with this JWT, backend should respond with the 401 UnAuthorized response. This behavior is applicable for all the endpoint where valid JWT is needed to access it.

public class TokenAuthenticator implements Authenticator {
public Request authenticate(Route route, Response response) throws IOException {
if (response.code() == 401) {
Call<Void> refreshCall = refereshAccessToken(refereshToken);

//make it as retrofit synchronous call
Response<Void> refreshResponse = refreshCall.execute();
if (refreshResponse != null && refreshResponse.code() == 200) {
//read new JWT value from response body or interceptor depending upon your JWT availability logic
newCookieValue = readNewJwtValue();
return response.request().newBuilder()
.header("basic-auth", newCookieValue)
} else {
return null;
mHttpClient.authenticator(new TokenAuthenticator());



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store