Access $auth0 object in the Vue router

I used this quickstart tutorial for my Vue SPA. I am having trouble accessing the auth0 isAuthenticated property in the Vue router. The Auth0 VueJS tutorial does not provide any information on this. This is the contents of my router/index.js file. I have followed the Auth0 VueJS tutorial closely. I am able to authenticate the user, but I am not able to redirect them to the appropriate page.

Here is the content of my router/index.js.

import Vue from "vue";
import Router from "vue-router";
import Login from "@/views/Login.vue";
import AuthProfile from "../views/AuthProfile.vue";
import { authGuard } from "../auth/authGuard";
import { getInstance } from "../auth";
import store from "@/data-store/index";
import { RouteMeta } from "@/types";

Vue.use(Router);
let auth0Code = null;
let auth0State = null;

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      name: "Home"
    },
    {
      path: "/login",
      name: "login",
      component: Login
    },
    {
      path: "/authprofile",
      name: "authprofile",
      component: AuthProfile,
      beforeEnter: authGuard
    }
  ]
});
export default router;

router.beforeEach((to, from, next) => {
  const authService = getInstance();
  console.log(authService.isAuthenticated);
  if (!authService.isAuthenticated) {
    console.log("isAuthenticated: ", authService.isAuthenticated);
    if (to.fullPath.includes("code")) {
      console.log("redirect path: ", next);
      auth0Code = to.query.code;
      console.log("includes code: ", auth0Code);
      auth0State = to.query.state;
      console.log("includes state: ", auth0State);
    }
    if (to.path === "/login" || to.path.includes("/forgot-password")) {
      return next();
    } else {
      return next({
        path: "/login",
        query: to.path.includes("logout") ? null : { from: to.fullPath }
      });
    }
  }
  // If the user tries to go to the login route manually and they
  // are already logged in, don't allow it.
  if (authService.isAuthenticated && to.path === "/login") {
    return next({ path: "/" });
  }

  // Redirect to the auth0 profile page when authenticated
  if (to.fullPath === "/" && authService.isAuthenticated) {
    return next({ path: "/authprofile" });
  }
});

The authService.isAuthenticated is always set to false and does not get updated.

Hi @katerina.chinnappan ,

Could you kindly check the answer given by @steve.hobbs here? - The prototype this.$auth in Vue main.js always null - #4 by steve.hobbs it could be related to your question.

I’m not an expert in JS so I’m not sure your use case on router.beforeEach logic. Could you kindly explain a bit more about it? aren’t you able to achieve the same results using the authWrapper.js and authGuard.js examples given in the Vue Quickstart?

Thank you!

1 Like