diff --git a/webapp/src/app/core/security/keycloak.service.ts b/webapp/src/app/core/security/keycloak.service.ts index 432210e2..cfd61d7c 100644 --- a/webapp/src/app/core/security/keycloak.service.ts +++ b/webapp/src/app/core/security/keycloak.service.ts @@ -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) { @@ -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(); }