Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keycloak is not initialized in router middleware #15

Open
askareija opened this issue Jul 12, 2022 · 0 comments
Open

Keycloak is not initialized in router middleware #15

askareija opened this issue Jul 12, 2022 · 0 comments

Comments

@askareija
Copy link

I try to use vue router middleware for guarding routes that needs user to be authenticated. I try to get isPending value, but it's always return true. How to await keycloak initialization finished then guard the route app?

here's my main.ts code:

import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import routes from "./routes";
import "./assets/css/index.css";
import { vueKeycloak } from "@baloise/vue-keycloak";
import { createPinia } from "pinia";

const app = createApp(App);
const router = createRouter({ history: createWebHistory(), routes: routes });
app.use(createPinia());

app.use(vueKeycloak, {
  initOptions: {
    checkLoginIframe: false,
    onLoad: "check-sso",
    silentCheckSsoRedirectUri:
      window.location.origin + "/assets/silent-check-sso.html",
  },
  config: {
    url: import.meta.env.VITE_SSO_URL,
    realm: import.meta.env.VITE_SSO_REALM,
    clientId: import.meta.env.VITE_SSO_CLIENT_ID,
  },
});
console.log('keycloak initialized. run application.')
console.log('START: using router')
app.use(router);
console.log('END: using router')

app.mount("#app");

here's my auth guard route middleware code (for now):

import { getToken, useKeycloak } from "@baloise/vue-keycloak";
const { keycloak, isPending, isAuthenticated } = useKeycloak();

const authGuard = async (to: any, from: any) => {
  console.log(isPending.value);
  try {
    console.log("is pending: ", isPending.value);
    if (!isPending.value) {
      console.log(`is pending is false.`);
      console.log(isAuthenticated.value);
      const token = await getToken();

      if (!isAuthenticated.value) {
        alert("Sesi anda sudah habis. Silakan untuk login kembali.");
        return "/";
      }
    }
  } catch (error) {
    alert(error);
    return "/";
  }
};

export default authGuard;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant