vue.js - 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 中不起作用?
解决方案
解决了!
中间件可以是异步的。为此,请返回一个 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 块之外的承诺。
推荐阅读
- javascript - 创建 ms 团队应用程序中的 javascript 实现问题
- javascript - 没有得到第三个条件
- spring - 为什么这个条件批处理流包含在spring批处理的无限循环中?
- c++ - C++中的基本类继承
- excel - 如果值包含未转义的逗号,是否有一种简单的方法来解析 Excel、Power Query 或 VBA 中逗号分隔的键:值对?
- plot - Gnuplot 数据符合日志函数
- python - 在 Pandas 中创建多索引标头
- angular - 适用于 Visual Studio Code 的 Microsoft Edge 开发人员工具不会自动将调试器附加到 Angular 项目
- python - 如何根据外键列出所有产品?
- java - 使用特定 Maven 配置文件运行 Spring Boot 应用程序时如何禁用 Keycloak 身份验证?