import Keycloak from 'keycloak-js'; import { useEffect, useState } from 'react'; const kc = new Keycloak({ url: process.env.KEYCLOAK_URL as string, realm: process.env.KEYCLOAK_REALM as string, clientId: process.env.KEYCLOAK_CLIENT as string, }); const initKeycloak = () => { return kc.init({ onLoad: 'check-sso', silentCheckSsoRedirectUri: window.location.origin + "/silent-check-sso.html", checkLoginIframe: false, pkceMethod: 'S256', }); }; export default function useKeycloakAuth() { const [authenticated, setAuthenticated] = useState(null); useEffect(() => { initKeycloak().then(auth => { setAuthenticated(auth); }); // Handle token expiration if (kc.onTokenExpired) { kc.onTokenExpired = () => kc.updateToken().then(() => setAuthenticated(true)); } // Listen for authentication events kc.onAuthSuccess = () => setAuthenticated(true); kc.onAuthError = () => setAuthenticated(false); kc.onAuthLogout = () => setAuthenticated(false); }, []); return { authenticated, keycloak: kc }; }