I'm using keycloak-js adapter with a Vue 3 Application. This system has some public pages, so I can't call keycloak right away. I already setup a button to call the login page, but the token is not being setup in the localStorage.
Basically my user flow need to be: Landing page > Clicks login button > Go to keycloak login page > redirects to a page where i make a request to return the user roles > get the user rows and redirects to the right page.
My request need a token and I can get to the redirection page, but the request fails because I don't have a token or a refresh token. Also, it give TypeError: adapter is undefined error when I try something different
Heres is my keycloak init function. If I change the onLoad option to check-sso, it returns #error=login_required&state=c7d6d227-5b23-4b21-962a-8e6291545f55. So login-required is working 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);
});
}
and heres a guard I made 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 tried changing the keycloak init options and making guards for my routes, so I can check is has a token, but they also doesnt seem to work. I expect to have a flow where some pages are public and other are protected by keycloak