Nuxt对接Laravel Sanctum登录报错:Token与Refresh Token均已过期
解决Nuxt + Laravel Sanctum登录时的"Both token and refresh token have expired"报错
从你描述的情况(直接调用接口正常,但通过nuxt-auth-next登录报错)来看,问题肯定出在nuxt-auth-next的配置和Sanctum的会话认证机制不匹配上,咱们一步步排查:
1. 修正nuxt-auth的Local策略配置
你当前的local策略设置了tokenRequired: false和tokenType: false,这是对的(因为Sanctum用HTTP-only cookie而非JWT token),但还需要明确告诉nuxt-auth咱们用cookie会话而非token认证,同时补充登出接口的配置:
修改nuxt.config.js里的auth.strategies.local:
local: { endpoints: { login: { url: '/login', method: 'post', propertyName: false }, user: { url: '/api/user', method: 'get', propertyName: false }, logout: { url: '/logout', method: 'post' } // 新增登出接口,确保会话正确销毁 }, tokenRequired: false, tokenType: false, cookie: { options: { sameSite: 'lax' // 匹配Sanctum的cookie设置,避免跨域问题 } } }
2. 调整Login.vue的登录逻辑
你的代码里有个小问题:then回调里的user变量未定义,另外可以在登录前重置auth状态,避免旧的过期token缓存干扰:
<script> export default { data() { return { form: { email: '', password: '' }, errors: {} }; }, methods: { async login () { try { // 重置auth状态,清除可能存在的过期缓存 await this.$auth.reset() // 获取CSRF cookie await this.$axios.$get('/sanctum/csrf-cookie'); // 执行登录 await this.$auth.loginWith('local', { data: this.form }) // 用this.$auth.user获取用户信息,替代未定义的user变量 console.log('登录成功,用户信息:', this.$auth.user) this.$router.push('/') } catch ({ response }) { console.log(response.data.errors); this.errors = response.data.errors } } } }; </script>
3. 确认Laravel Sanctum的跨域配置
虽然你直接调接口正常,但还是要确保后端的跨域配置正确,避免cookie无法传递:
- 在
.env里设置:SANCTUM_STATEFUL_DOMAINS=localhost:3000 # Nuxt的运行端口 SESSION_DOMAIN=.localhost # 允许子域共享cookie,注意前面的点 - 确保
config/cors.php里的supports_credentials设置为true:'supports_credentials' => true,
4. 清除浏览器缓存测试
有时候浏览器会缓存过期的cookie或auth状态,建议打开无痕模式测试,或者手动清除当前站点的缓存和cookie。
为什么直接调接口正常?
因为你直接在控制台调用接口时,浏览器会自动处理CSRF cookie和会话cookie的传递,但nuxt-auth-next内部有自己的状态管理逻辑,如果配置不匹配,它会错误地认为token过期(其实咱们根本没在用token),从而抛出这个错误。
内容的提问来源于stack exchange,提问作者ExtraVagant Virtouso
相关产品推荐
相关产品推荐

