【问题标题】:Auth0 route guard not working with Nuxt middlewareAuth0 路由保护不适用于 Nuxt 中间件
【发布时间】:2021-07-05 18:34:34
【问题描述】:

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

我已调整 Auth0 sample code 以创建以下中间件:

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 完成加载并且可以访问其身份验证状态?

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

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js auth0


    【解决方案1】:

    解决了!

    中间件可以是异步的。为此,请返回一个 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 块之外的承诺也很重要。

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 2021-09-06
      • 2015-12-17
      • 2022-11-16
      • 2019-10-05
      相关资源
      最近更新 更多