Nuxt实现无按钮自动跳转Google登录的问题求助
解决Nuxt Google登录循环跳转问题
核心问题原因
你在登录页的created/mounted钩子中无条件调用loginWith,导致Google授权回调携带code参数返回登录页时,再次触发跳转逻辑,形成循环。
解决方案
1. 修改登录页逻辑,添加回调参数判断
在登录页组件中,仅当用户未登录且URL中没有OAuth2授权回调的code参数时,才触发登录跳转:
<template> <!-- 登录页内容可留空,因为会自动跳转 --> </template> <script> export default { created() { const hasAuthCode = this.$route.query.code // 未登录且无回调code时,触发Google登录 if (!this.$auth.loggedIn && !hasAuthCode) { this.$auth.loginWith('social') } // 已登录则直接跳转至受限页面 else if (this.$auth.loggedIn) { this.$router.push('/dashboard') } } } </script>
2. 完善auth配置的跳转规则
在nuxt.config.js的auth配置中添加redirect选项,明确回调页面和登录成功后的跳转目标:
auth: { strategies: { // 保留你原有的social策略配置 social: { scheme: 'oauth2', endpoints: { authorization: 'https://accounts.google.com/o/oauth2/auth', token: 'http://localhost:4000/api/auth/google/token', refresh: 'http://localhost:4000/api/auth/google/refresh' }, user: { autoFetch: false, }, token: { property: 'access_token', type: 'Bearer', }, refreshToken: { property: 'refresh_token', maxAge: 60 * 60 * 24 * 30 }, responseType: 'code', clientId: '<clientId>', // 替换为你的实际Client ID scope: ['openid', 'profile', 'email'], state: 'UNIQUE_AND_NON_GUESSABLE', codeChallengeMethod: '', responseMode: '', acrValues: '', } }, // 添加跳转规则 redirect: { login: '/login', // 未认证时跳转的登录页 home: '/dashboard', // 登录成功后默认跳转的受限页面 callback: '/login' // OAuth2授权回调页面,设为登录页即可 } },
3. 用auth中间件保护受限路由
为受限页面添加auth中间件,自动拦截未认证用户并跳转至登录流程:
- 全局配置(所有路由都受保护):在
nuxt.config.js中添加
router: { middleware: ['auth'] }
- 单个页面配置(仅当前页面受保护):在目标页面组件中添加
<script> export default { middleware: 'auth' } </script>
原理说明
当用户未访问过登录页时,会触发loginWith跳转至Google授权页;授权完成后,Google会携带code参数跳回登录页,此时代码检测到code存在,不再触发跳转,Nuxt Auth模块会自动用code换取token,完成认证后跳转至home配置的受限页面。
内容的提问来源于stack exchange,提问作者pipo92
相关产品推荐
相关产品推荐

