3

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.

naffie
  • 679
  • 1
  • 12
  • 29

1 Answers1

0

I was getting the same behavior as yours with appAuth and Keycloak. This seams to be related to the settings in Keycloak for your realm.

This answer nailed the problem for me (https://stackoverflow.com/a/67624190/2259378)

In summary, the maximum lifetime for refresh token is the lesser value from this four variables in Keycloak: (SSO Session Idle, Client Session Idle, SSO Session Max, and Client Session Max)