diff --git a/src/app/auth/auth.guard.ts b/src/app/auth/auth.guard.ts new file mode 100644 index 0000000..c134bd4 --- /dev/null +++ b/src/app/auth/auth.guard.ts @@ -0,0 +1,12 @@ +import { inject } from '@angular/core'; +import { CanActivateFn } from '@angular/router'; +import { KeycloakService } from './keycloak.service'; + +export const authGuard: CanActivateFn = () => { + const keycloak = inject(KeycloakService); + if (keycloak.isLoggedIn()) { + return true; + } + keycloak.login(); + return false; +}; diff --git a/src/app/auth/keycloak.service.ts b/src/app/auth/keycloak.service.ts new file mode 100644 index 0000000..9517750 --- /dev/null +++ b/src/app/auth/keycloak.service.ts @@ -0,0 +1,43 @@ +import { Injectable, signal } from '@angular/core'; +import Keycloak from 'keycloak-js'; + +@Injectable({ providedIn: 'root' }) +export class KeycloakService { + private readonly keycloak = new Keycloak({ + url: 'https://auth.goutailler-olivier.com', + realm: 'bonsai', + clientId: 'bonsai-webapp', + }); + + readonly isAuthenticated = signal(false); + readonly username = signal(undefined); + + async init(): Promise { + try { + const authenticated = await this.keycloak.init({ + onLoad: 'check-sso', + silentCheckSsoRedirectUri: `${window.location.origin}/assets/silent-check-sso.html`, + pkceMethod: 'S256', + }); + this.isAuthenticated.set(authenticated); + if (authenticated) { + this.username.set(this.keycloak.tokenParsed?.['preferred_username']); + this.keycloak.onTokenExpired = () => this.keycloak.updateToken(30).catch(() => this.logout()); + } + } catch { + console.error('Échec de l\'initialisation Keycloak'); + } + } + + login(): Promise { + return this.keycloak.login(); + } + + logout(): Promise { + return this.keycloak.logout({ redirectUri: window.location.origin }); + } + + isLoggedIn(): boolean { + return this.keycloak.authenticated ?? false; + } +} diff --git a/src/assets/silent-check-sso.html b/src/assets/silent-check-sso.html new file mode 100644 index 0000000..5357587 --- /dev/null +++ b/src/assets/silent-check-sso.html @@ -0,0 +1,8 @@ + + + + + +