簡體   English   中英

Auth0 路由保護不適用於 Nuxt 中間件

[英]Auth0 route guard not working with Nuxt middleware

在 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 完成加載並且可以訪問其身份驗證狀態?

我還嘗試在 Nuxt 頁面的beforeRouteEnter掛鈎中使用 Auth0 提供的幾乎完全相同的代碼,而無需我自己修改。 這有同樣的問題,這引出了一個問題,即為什么 Auth0 示例可能在 VueJS 中使用beforeRouteEnter而不是在 Nuxt 中工作?

解決了!

中間件可以是異步的。 為此,請返回 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以確保它沒有打開 go 來解析 if 塊之外的 promise 也很重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM