Home:ALL Converter>'Refresh token expired exception' - AppAuth Android

'Refresh token expired exception' - AppAuth Android

Ask Time:2020-04-21T15:54:00         Author:naffie

Json Formatter

I'm using appAuth with Keycloak for authentication in my android app. After about 25 minutes, the access token expires. When I try to refresh the token after this period, I get this error:

Failed to authorize = AuthorizationException: {"type":2,"code":2002,"error":"invalid_grant","errorDescription":"Refresh token expired","errorUri":""}

To refresh the token, I'm calling performActionWithFreshTokens and passing in the refreshToken I received earlier from the TokenResponse.

Map<String, String> refreshTokenAdditionalParams = new HashMap<>();
refreshTokenAdditionalParams.put(Constants.REFRESH_TOKEN,getAuthState().getRefreshToken());
Log.i(TAG, "Refresh Token from AuthState:"+ getAuthState().getRefreshToken());

mAuthStateManager.getCurrent().performActionWithFreshTokens(mAuthService,clientAuthentication,refreshTokenAdditionalParams, (accessToken, idToken, ex) -> {
    Log.i(TAG, "Access Token :"+ accessToken + "id Token :"+ idToken );
    Log.i(TAG, "Token Response :"+ mAuthStateManager.getCurrent().getLastTokenResponse());
    if (ex != null) {
        // negotiation for fresh tokens failed, check ex for more details
        if (ex.errorDescription.contains(Constants.TOKEN_EXPIRED)) {
            CommonHelper.getAccessDeniedFailure(false);
            return;
        }
    }

    mAuthStateManager.getCurrent().update(mAuthStateManager.getCurrent().getLastTokenResponse(), ex);
    if (getAuthState().isAuthorized()) {
        SessionManager.UserDetail detail = sessionManager.getUserDetails();
        if (detail == null) {
            detail = new SessionManager.UserDetail();
        }
        detail.updateAuthToken(getAuthState().getAccessToken());
        detail.updateRefreshToken(getAuthState().getRefreshToken());
        sessionManager.createUserSession(detail);
        sessionManager.setLastActivityTime(System.currentTimeMillis());
    }
    callback.onTokenRequestCompleted(mAuthStateManager.getCurrent().getLastTokenResponse(), ex);

});

Before deciding to pass in the refreshToken as additionalParameters in the function, I thought the fact that I'm calling performActionWithFreshTokens would automatically solve this exception. I still got the error. Then I decided to pass in the refreshToken as a parameter but I still get the exception and the returned accessToken and idToken are null.

I'm not sure how else to resolve this issue. Has anyone else faced this issue? Thanks.

Author:naffie,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61338509/refresh-token-expired-exception-appauth-android
yy