You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Nuxt 3中使用sidebase/nuxt-auth及GoogleProvider获取Laravel授权Token

问题分析与解决方案

你的当前token选项使用方式不正确,@sidebase/nuxt-auth 基于 NextAuth.js 实现,其 OAuth 流程配置逻辑和 Nuxt 2 的 auth 模块差异较大,仅指定token.url无法引导流程向你的 Laravel 后端交换自定义 token,默认仍会走谷歌原生的 token 交换流程,因此account中的 token 还是谷歌返回的。

正确配置方式

要实现通过 Laravel 后端获取自定义access_token,需要完整覆盖 GoogleProvider 的授权与 token 交换流程,让 NextAuth.js 将谷歌授权得到的 code 传递给你的 Laravel 接口,再提取后端返回的 token:

1. 调整 GoogleProvider 配置

GoogleProvider.default({
  clientId: '你的谷歌clientId.apps.googleusercontent.com',
  clientSecret: '你的谷歌clientSecret',
  // 指定谷歌授权端点,确保返回 authorization code
  authorization: {
    url: 'https://accounts.google.com/o/oauth2/v2/auth',
    params: {
      scope: 'openid email profile',
      response_type: 'code'
    }
  },
  // 核心:指定 Laravel 的 token 交换接口
  token: {
    url: 'https://api.example.com/api/auth/socialite/google',
    method: 'POST', // 按 Laravel Socialite 接口的请求方式调整
    params: {
      grant_type: 'authorization_code' // 标准 OAuth2 授权码模式参数
    },
    // 指定从 Laravel 返回结果中提取 access_token 的字段名
    property: 'access_token',
    // 如果后端返回了 refresh_token,也可在此指定字段
    // refresh_token: 'refresh_token'
  },
  // 可选:如果需要从 Laravel 获取用户信息,配置 userinfo 端点
  userinfo: {
    url: 'https://api.example.com/api/user',
    method: 'GET',
    headers: {
      Authorization: ({ tokens }) => `Bearer ${tokens.access_token}`
    }
  }
})

2. 更新 jwt 回调

此时account参数会携带 Laravel 返回的 token 数据,需要将其存入 jwt 中:

async jwt({ token, account }) {
  if (account) {
    // 存储 Laravel 返回的 token 信息
    token.access_token = account.access_token;
    token.refresh_token = account.refresh_token;
    token.expires_at = account.expires_at;
  }
  return token;
}

3. 确保 Session 策略配置

在nuxt.config.ts的 auth 配置中,设置 session 策略为jwt,确保自定义 token 能被正确存储和使用:

export default defineNuxtConfig({
  modules: ['@sidebase/nuxt-auth'],
  auth: {
    session: {
      strategy: 'jwt'
    }
  }
})

配置逻辑说明

Nuxt 2 的 auth 模块通过endpoints和token.property就能简单引导流程到后端接口,但 NextAuth.js 对 OAuth 流程的控制更细致,需要明确指定授权端点、token 交换的请求方式/参数、响应字段映射,才能覆盖默认的谷歌 token 交换流程,实现与 Laravel 后端的对接。

内容的提问来源于stack exchange,提问作者sunergos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 10:13:20