【发布时间】: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