[Vuejs]-KeyCloak-js and vue3 – Need some pages to be public

0👍

This is how I have setup keycloak in my Vue.js app. I have two pages that are public and the rest of them are private and accessed after keycloak authentication.

    import Keycloak from "keycloak-js";
    import useStore from "./store";
    
    const initOptions = {
      realm: import.meta.env.VITE_KEYCLOAK_REALM_NAME,
      clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID,
      url: import.meta.env.VITE_KEYCLOAK_SERVER_URL,
      "public-client": true,
      "verify-token-audience": false,
    };
    
    const keycloak = Keycloak(initOptions);
    
    async function initKeycloak() {
      const store = useStore();
    
      await keycloak
        .init({onLoad: "check-sso", redirectUri: import.meta.env.VITE_KEYCLOAK_REDIRECT_URI})
        .then(async (auth) => {
          if (!auth) {
            store.unauthenticate();
          } else {
            await store.authenticate();
            if (keycloak.token) {
              store.token = keycloak.token;
              store.userRoles = keycloak.tokenParsed.realm_access.roles;
              window.localStorage.setItem("keycloakToken", keycloak.token);
            }
          }
        });
      setInterval(() => {
        keycloak
          .updateToken(70)
          .then((refreshed) => {
            if (refreshed) {
              store.token = keycloak.token;
              window.localStorage.setItem("keycloakToken", keycloak.token);
              console.info("Token refreshed" + refreshed);
            } else {
              console.warn(
                "Token not refreshed, valid for " +
                  Math.round(
                    keycloak.tokenParsed.exp +
                      keycloak.timeSkew -
                      new Date().getTime() / 1000
                  ) +
                  " seconds"
              );
            }
          })
          .catch(() => {
            console.error("Failed to refresh token");
          });
      }, 3000);
    }
    
    export async function keycloakLogin() {
      keycloak.login();
    }
    
    // keycloak logout
    var logoutOptions = {redirectUri: import.meta.env.VITE_KEYCLOAK_REDIRECT_URI};
    
    function keycloakLogout() {
      keycloak
        .logout(logoutOptions)
        .then((success) => {
          console.log("--> log: logout success ", success);
        })
        .catch((error) => {
          console.log("--> log: logout error ", error);
        });
    }

I’m not sure why you’re using the KeycloakInstance maybe you’ve declared it on top of the file. I’m just using the keycloakLogin method on my landing page which is public and has the login button.

On click of the login button the keycloakLogin method is called and it redirects to the auth server. And after successful authentication it redirects to the redirectUri which is present in my .env.

I hope this helps.

Leave a comment