auth0 / auth0-vue

Auth0 authentication SDK for Vue.js apps
Other
140 stars 27 forks source link

Please ensure Auth0's Vue plugin is correctly installed. error #425

Closed Fukao0129 closed 1 month ago

Fukao0129 commented 1 month ago

Checklist

Description

I'm using Nuxt3.

plugins/auth0.ts

import { createAuth0 } from "@auth0/auth0-vue";

export default defineNuxtPlugin((nuxtApp) => {
  const auth0 = createAuth0({
    domain: `{my-domain},
    clientId: `{my-clientId},
    authorizationParams: {
      redirect_uri: `{my-domain}/callback/`,
      scope: "openid profile email",
      audience: {my-audience},
    },
  });

  nuxtApp.vueApp.use(auth0);
});

This seems to be working well.

Then, I used the authGuard like this.

import type { RouterConfig } from "@nuxt/schema";
import { authGuard } from "@auth0/auth0-vue";

const routerConfig: RouterConfig = {
  routes: (_routes) => {
    let route = _routes;
    route.forEach((r) => {
      if (r.path !== "/callback" && r.path !== "/login") {
        r.beforeEnter = authGuard;
      }
    });

    return route;
  },
};

export default routerConfig;

In this situation, when I reload the page, "Please ensure Auth0's Vue plugin is correctly installed" error occurs.

■When I'm authenticated...
The screen momentarily displays an error message, and then immediately shows the page I was looking at before reloading.

■When I'm unauthenticated... The screen momentarily displays an error message, and then immediately shows the universal login screen. After I login, SDK redirects to the page I was looking at before reloading.

Except for a momentary error, it works as expected. Is there something wrong with my authGuard setup?

Reproduction

Step1. Reload a page that is auth guarded.

Additional context

[nuxt] error caught during app initialization H3Error: Navigation aborted from "/" to "/" via a navigation guard. at createRouterError (

auth0-vue version

2.3.3

Vue version

Vue 3.5.10 / Nuxt 3.13.0

Which browsers have you tested in?

Chrome, Edge, Firefox

Fukao0129 commented 1 month ago

The cause was that router.option.ts was executed before the SDK initialization by plugins. By moving the authGuard setup to a middleware that executes after the plugins, I resolved this issue.

import { authGuard } from "@auth0/auth0-vue";

export default defineNuxtRouteMiddleware((to, from) => {
  router.options.routes.forEach(async (route) => {
    if (to.path !== "/callback/" && to.path !== "/login/") {
      return await authGuard(to);
    }
  });
});

I'm not sure this is a correct approach, but this seems to be working well so far, so I close this issue.