Currently, I am integrating keycloak-js adapter into a Vue 3 Application. The challenge I am facing is with the system's public pages, which prevent me from calling Keycloak immediately. Even though I have set up a button to trigger the login page, the token is not getting stored in the localStorage.
The desired user flow should be: Landing page > Click login button > Redirect to Keycloak login page > Redirect to a page where a request for user roles is made > Obtain user roles and redirect to the appropriate page.
I am encountering an issue where my request requires a token but fails due to the absence of a token or refresh token. Additionally, when attempting a different approach, it gives a TypeError: adapter is undefined error.
Here is my keycloak init function. When I change the onLoad option to check-sso, it returns #error=login_required&state=c7d6d227-5b23-4b21-962a-8e6291545f55, indicating that login-required is functioning correctly for me.
const Login = () => {
KeyCloakInstance.init({ onLoad: "login-required", checkLoginIframe: true,
redirectUri: window.location.origin + "/redirect" })
.then((authenticated) => {
console.log("Keycloak Authenticated", authenticated)
if (authenticated) {
console.log("Authentication Success")
KeyCloakInstance.authenticated = true;
} else {
console.log("Authentication Failed")
}
localStorage.setItem('token', KeyCloakInstance.token as string);
localStorage.setItem('refreshToken', KeyCloakInstance.refreshToken as string);
}).catch((err) => {
console.dir(err);
console.log("Authentication Failed", err);
});
}
Below is the guard I created for the routes:
import { getRole } from "@/services/config";
import Keycloak from "keycloak-js";
function guardAuth(to: any, from: any, next: any){
const hasUser = localStorage.getItem("token");
const isMeta = "auth" in to.meta;
const metaAuth = to.meta.auth;
if(isMeta && metaAuth && !hasUser){
const keycloakInst = new Keycloak({
url: "http://localhost:8082/",
realm: "APP",
clientId: "live_app"
});
keycloakInst.login();
} else if(isMeta && !metaAuth && hasUser){
RoleType(hasUser, next);
} else {
next();
}
}
function RoleType(user: any, next: any): void{
if(getRole() == user.role_portal){
next('/redirect');
} else {
next('/');
}
}
export { guardAuth };
I have experimented with changing the keycloak init options and creating guards for my routes in order to verify if there is a token present, but they do not seem to be effective. My aim is to establish a flow where some pages are publicly accessible while others are protected by Keycloak.