我在Nuxt3中使用Auth0构建了一个简单的登录页面,它可以工作。现在,我正在尝试构建一个中间件,它将重定向未经身份验证的用户到登录页面。我可以在login.vue页面上使用$auth0.isAuthenticated变量,但在我的中间件中不能使用,因为我得到错误“无法读取未定义的属性(读取'$auth0')”。如何从中间件访问isAuthenticated变量?
这是登录页面: pages/login.vue
<template>
<div>
<p v-if="isAuthenticated">hey {{ user }}</p>
<p v-else>you are not authenticated</p>
<button @click="login">Log in</button>
<button @click="logout">logout</button>
</div>
</template>
<script>
export default {
data() {
return {
user: this.$auth0.user,
isAuthenticated: this.$auth0.isAuthenticated
};
},
methods: {
login() {
this.$auth0.loginWithRedirect();
},
logout() {
this.$auth0.logout({ returnTo: 'http://localhost:3000' });
}
},
};
</script>
这是中间件页面(中间件/auth.global.ts)
export default defineNuxtRouteMiddleware(() => {
if (this.$auth0.isAuthenticated) {
console.log('authenticated')
}
else {
console.log('not authenticated')
}
})
发布于 2022-08-08 13:55:43
我尝试了中间件方法,但一直面临着同样的问题。
最后,我在布局的<script setup>
部分完成了以下操作:
import { authGuard } from "@auth0/auth0-vue";
const thisRouter = useRouter();
thisRouter.beforeEach(authGuard);
我觉得这不是百分之百正确,但它似乎是有效的。
https://stackoverflow.com/questions/72369904
复制相似问题