Skip to content

Commit

Permalink
Fix: Keycloak Refresh Tokens before Expiry (#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
GODrums authored Nov 27, 2024
1 parent db7f35e commit 2e8e6ca
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions webapp/src/app/core/security/keycloak.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface UserProfile {
export class KeycloakService {
_keycloak: Keycloak | undefined;
profile: UserProfile | undefined;
tokenRefreshInterval = 60; // in seconds

get keycloak() {
if (!this._keycloak) {
Expand All @@ -44,9 +45,29 @@ export class KeycloakService {
this.profile = (await this.keycloak.loadUserInfo()) as unknown as UserProfile;
this.profile.token = this.keycloak.token || '';
this.profile.roles = this.keycloak.realmAccess?.roles || [];

// Check refresh token expiry
setInterval(() => {
this.updateToken();
}, this.tokenRefreshInterval * 1000);

return true;
}

private async updateToken() {
try {
// Try to refresh token if it's about to expire
const refreshed = await this.keycloak.updateToken(this.tokenRefreshInterval + 10);
if (refreshed) {
this.profile!.token = this.keycloak.token || '';
}
} catch (error) {
console.error('Failed to refresh token:', error);
// Redirect to login if refresh fails
await this.keycloak.login();
}
}

login() {
return this.keycloak.login();
}
Expand Down

0 comments on commit 2e8e6ca

Please sign in to comment.