首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查用户是否从Nuxt3 Auth0中的中间件中登录

如何检查用户是否从Nuxt3 Auth0中的中间件中登录
EN

Stack Overflow用户
提问于 2022-05-24 21:57:20
回答 1查看 233关注 0票数 0

我在Nuxt3中使用Auth0构建了一个简单的登录页面,它可以工作。现在,我正在尝试构建一个中间件,它将重定向未经身份验证的用户到登录页面。我可以在login.vue页面上使用$auth0.isAuthenticated变量,但在我的中间件中不能使用,因为我得到错误“无法读取未定义的属性(读取'$auth0')”。如何从中间件访问isAuthenticated变量?

这是登录页面: pages/login.vue

代码语言:javascript
运行
复制
<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)

代码语言:javascript
运行
复制
export default defineNuxtRouteMiddleware(() => {
  if (this.$auth0.isAuthenticated) {
    console.log('authenticated')
  }
  else {
    console.log('not authenticated')
  }
})
EN

回答 1

Stack Overflow用户

发布于 2022-08-08 13:55:43

我尝试了中间件方法,但一直面临着同样的问题。

最后,我在布局的<script setup>部分完成了以下操作:

代码语言:javascript
运行
复制
import { authGuard } from "@auth0/auth0-vue"; 

const thisRouter = useRouter();

thisRouter.beforeEach(authGuard);

我觉得这不是百分之百正确,但它似乎是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72369904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档