mauriciovigolo / keycloak-angular

Easy Keycloak setup for Angular applications.
MIT License
730 stars 280 forks source link

Token refresh fails with 400 invalid_grant Token is not active #564

Closed kimwykoff closed 3 months ago

kimwykoff commented 6 months ago

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search for issues before submitting
- [ ] feature request

Versions.

keycloak-angular: 14.2.0 angular: 16.2.12 keycloak-js: 23.0.4 keycloak: 23.0.4

Repro steps.

My app is reloading quite frequently (about every 5 minutes). I have added a listener for keycloak events like this:

this.keycloakService.keycloakEvents$
      .subscribe((event) => {
        if (event.type === KeycloakEventType.OnTokenExpired) {
          console.log('OnTokenExpired');
          this.keycloakService.updateToken(20)
            .then(function (refreshed) {
              if (refreshed) {
                console.log('Token was successfully refreshed');
              } else {
                console.log('Token is still valid');
              }
            })
            .catch(function () {
              // auth.logout();
              console.log('Failed to refresh the token, or the session has expired');
            });
        }
      });
  }

It issues an openid-connect/token http call and I noticed that it gets an error response: {"error":"invalid_grant","error_description":"Token is not active"} image

They payload is something like: grant_type: refresh_token refresh_token: long_token client_id: my_client

After that failure, the next event is a logout and then my app reloads.

I see that keycloak-angular 14 depends on keycloak-js 24. Could that be the problem? but keycloak-angular 13 depends on keycloak-js 21.

The log given by the failure.

Desired functionality.

kimwykoff commented 6 months ago

It seems to have more to do with the different timeout settings on the keycloak server. Also, the code is a bit wrong. When refreshed is false, then the token is no longer valid for various reasons. So in that case, I should just let the app reload.

kimwykoff commented 3 months ago

It's normal behavior