From 2e8e6cad0472e40b5a21492248a8cf7837a76aa4 Mon Sep 17 00:00:00 2001 From: Armin Stanitzok <21990230+GODrums@users.noreply.github.com> Date: Wed, 27 Nov 2024 10:08:22 +0100 Subject: [PATCH] Fix: Keycloak Refresh Tokens before Expiry (#190) --- .../src/app/core/security/keycloak.service.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) 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(); }