Home » Android » Authorization header request won't be modified in authenticate

Authorization header request won't be modified in authenticate

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m calling an API endpoint with Retrofit in my application. Each request is intercepted and adds a Bearer token as Authorization header. When the request returns 401, my Authenticator using authenticate intercepts that particular call and tries to refresh the token.

Everything works just fine until when I’m trying to modify that current request with a new authorization header token that I receive from the refresh token call. It won’t get updated, still keeps the old Authorization header which results in multiple subsequent 401 responses and finally logouts the user.

This is the specific code that doesn’t want to modify the authorization header

request.newBuilder().header("Authorization", "Bearer " + tokenResponse.getAccessToken()).build();

This is the complete authenticate

@Nullable
@Override
public Request authenticate(Route route, Response response) throws IOException {

    Request request = response.request();

    // If the request is to login or there isn't any account, stop and return this authentication.
    if (route.address().url().toString().equals(mApplication.getString(R.string.api_core_endpoint)) || mAccount == null) return null;

    if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED){
        mAccountService.refreshAccessTokenObs("refresh_token", mAccountManager.getPassword(mAccount), "inspection-api", "secret")
                .subscribe(tokenResponse -> {
                    if(tokenResponse.getAccessToken() != null) {
                        mAccountManager.setAuthToken(mAccount, mApplication.getString(R.string.auth_token_type), tokenResponse.getAccessToken());
                        mAccountManager.setPassword(mAccount, tokenResponse.getRefreshToken());

                        request.newBuilder() // <-- This row doesn't want to be modified! WTF so we fail refresh and will get logged out
                                .header("Authorization", "Bearer " + tokenResponse.getAccessToken())
                                .build();
                    } else {
                        mAccountManager.invalidateAuthToken(mApplication.getString(R.string.account_type), null); // force logout
                    }
                },error -> {

                },() -> {});

        return request;
    } else{
        return null;
    }
}
Answers: