Cristi Dumitrache
Cristi Dumitrache

Reputation: 150

Refresh Token Mechanism Iterates Forever in OkHttp Interceptor

I am working on implementing a refresh token mechanism in an OkHttp Interceptor, but it keeps iterating forever when the token refresh is needed. The issue seems to be that the responseCount(Response response) method always returns 1, which prevents the loop from breaking after the specified retries.

Here's the code for the responseCount method:

private int responseCount(Response response) {
    int result = 1;
    while ((response = response.priorResponse()) != null) {
        result++;
    }
    return result;
}

I suspect that response.priorResponse() is not working as expected within the Interceptor.

Here is the relevant code for the token refresh logic:

private Request getRequestWithNewToken(Response response) {
    Request request = null;
    try {
        if (semaphore.availablePermits() <= 0) {
            semaphore.release(1);
        }
        semaphore.acquire();
        final String authToken = authenticationServiceLazy.get()
                               .refreshAuthenticationTokens()
                               .blockingGet()
                               .getAuthToken();
        request = authenticatedRequestDecorator.decorateRequestWithToken(response.request(), authToken);
    } catch (Exception e) {
       logExceptionAndInterruptThread(e);
    }
    return request;
}

The semaphore is initialized as:

this.semaphore = new Semaphore(1);

And here is the intercept method:

@NonNull
@Override
public Response intercept(@NonNull Chain chain) {
    Request request;
    Response response = null;
    try {
        semaphore.acquire();
        request = chain.request();
        response = chain.proceed(request);
        if (response.code() == HTTP_UNAUTHORIZED && responseCount(response) <= RETRY_TIMES) {
            request = getRequestWithNewToken(response);
            if (request != null) {
                if (response.body() != null) {
                    response.close();
                }
                response = chain.proceed(request);
            }
        }
    } catch (Exception exception) {
        logExceptionAndInterruptThread(exception);
    } finally {
        semaphore.release();
        if (response == null) {
            response = internalErrorResponse(chain);
        }
    }
    return response;
}

Problem: The responseCount method always returns 1. response.priorResponse() doesn't seem to work as expected, causing the refresh mechanism to iterate indefinitely.

Question: How can I correctly count the prior responses to break out of the loop after a certain number of retries? Is there a better way to implement this refresh token mechanism in an OkHttp Interceptor?

Any help or insights would be greatly appreciated!

Upvotes: 0

Views: 22

Answers (0)

Related Questions