首页 > 解决方案 > Auth0 路由保护不适用于 Nuxt 中间件

问题描述

在 Nuxt 中实现 Auth0 路由保护的正确模式是什么?

我已经修改了Auth0 示例代码来创建以下中间件:

import {getInstance} from '~/plugins/auth';

export default function () {
  const authService = getInstance();

  const fn = () => {
    // If the user is authenticated, continue with the route
    if (!authService.isAuthenticated) {
      authService.loginWithRedirect({
        appState: {targetUrl: 'http://localhost:3000'},
      });
    }
  };

  // If loading has already finished, check our auth state using `fn()`
  if (!authService.loading) {
    return fn();
  }

  // Watch for the loading property to change before we check isAuthenticated
  authService.$watch('loading', loading => {
    if (loading === false) {
      return fn();
    }
  });
}

请注意,在可以访问 Auth0 的身份验证状态之前,我们必须等待实例完成加载。Auth0 示例代码使用$watch.

$watch我的中间件代码“有效”,但存在在异步触发之前短暂显示受保护页面的问题。有什么方法可以等待并阻止路由继续渲染,直到 Auth0 完成加载并且可以访问其身份验证状态?

我还尝试beforeRouteEnter在 Nuxt 页面的挂钩中使用几乎完全相同的 Auth0 提供的代码,而无需我自己修改。这有同样的问题,这引出了一个问题,即为什么 Auth0 示例可能在 VueJS 中使用beforeRouteEnter但在 Nuxt 中不起作用?

标签: vue.jsvuejs2nuxt.jsauth0

解决方案


解决了!

中间件可以是异步的。为此,请返回一个 Promise 或使用 async/await。

https://nuxtjs.org/docs/2.x/directory-structure/middleware/

我只是将我的中间件脚本包装在一个 Promise 中。如果用户能够通过,我解决了它,否则我将他们重定向到 Auth0 登录。

import {getInstance} from '~/plugins/auth';

export default function () {
  return new Promise(resolve => {
    const authService = getInstance();

    const fn = () => {
      // If the user is authenticated, continue with the route
      if (!authService.isAuthenticated) {
        return authService.loginWithRedirect({
          appState: {targetUrl: 'http://localhost:3000'},
        });
      }
      resolve();
    };

    // If loading has already finished, check our auth state using `fn()`
    if (!authService.loading) {
      return fn();
    }

    // Watch for the loading property to change before we check isAuthenticated
    authService.$watch('loading', loading => {
      if (loading === false) {
        return fn();
      }
    });
  });
}

返回也很重要,loginWithRedirect以确保它不会继续解决 if 块之外的承诺。


推荐阅读