Sharing this solution for future reference as Keycloak has undergone significant changes in recent versions, rendering old answers outdated.
Below is the method that successfully enabled logging in and out of Keycloak using a front-end application built with Vue 3 or Nuxt 3, along with the Keycloak-js library.
import Keycloak from "keycloak-js";
const config = useRuntimeConfig();
const initOptions = useState("initOptions", () => ({
realm: config.public.KEYCLOAK_REALM_NAME,
clientId: config.public.KEYCLOAK_CLIENT_ID,
url: config.public.KEYCLOAK_SERVER_URL,
}));
// Initializing Keycloak constructor
const keycloak = new Keycloak(initOptions.value);
//Function to login to Keycloak and generate token and ID token
export async function keycloakLogin() {
try {
// Initialize Keycloak and handle authentication
const auth = await keycloak.init({
onLoad: "login-required",
flow: "implicit",
});
// Reload if not authenticated to display login page
if (!auth) {
window.location.reload();
} else {
console.log("User is authenticated");
}
// Store tokens in local storage if present
if (keycloak.token) {
window.localStorage.setItem("keycloakToken", keycloak.token);
window.localStorage.setItem("idToken", keycloak.idToken);
}
// Initiating token checking
setupTokenChecking();
} catch (error) {
console.error("Error initializing Keycloak:", error);
}
}
export async function keycloakLogout() {
const logoutURL =
config.public.KEYCLOAK_LOGOUT_URL +
"?id_token_hint=" +
localStorage.getItem("idToken") +
"&post_logout_redirect_uri=" +
encodeURIComponent(window.location.href);
keycloak
.logout({ redirectUri: logoutURL })
.then((success) => {
console.log("User logout success ", success);
})
.catch((error) => {
console.log("User logout error ", error);
});
}
// Initial token check and periodic checks setup
async function setupTokenChecking() {
await checkAndRenewToken();
const tokenCheckInterval = 5 * 60 * 1000;
setInterval(checkAndRenewToken, tokenCheckInterval);
}
// Function to periodically check and renew Keycloak token
export async function checkAndRenewToken() {
try {
if (keycloak.isTokenExpired()) {
console.log("Token is expired. Renewing token...");
try {
await keycloak.updateToken(60);
} catch (error) {
console.error(
"Refresh Token Failed : " + JSON.stringify(error, null, 4)
);
window.location.reload();
}
}
} catch (error) {
console.error("Error checking/renewing token:", error);
}
}
The example URL configuration:
KEYCLOAK_REALM_NAME=myRealm
KEYCLOAK_CLIENT_ID=myClientID
KEYCLOAK_SERVER_URL=http://localhost:9080
KEYCLOAK_LOGOUT_URL=http://localhost:9080/realms/myRealm/protocol/openid-connect/logout
Keycloak no longer requires /auth
in the URLs as it did previously.