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

Vue3-google-login获取授权码后如何对接后端Passport认证?

解决Vue3中发送Google授权码到Passport后端完成认证的方案

核心思路

你的现有后端接口是为Google OAuth跳转回调设计的,而当前前端使用的是vue3-google-login的授权码模式(Code Flow),需要新增后端接口接收前端传来的授权码,验证后完成用户认证。


1. 后端新增授权码处理接口

首先安装Google官方认证库(Passport底层依赖它):

npm install google-auth-library

然后新增POST接口,用于接收并验证授权码:

const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(
  '你的Google Client ID', // 和前端配置的一致
  '你的Google Client Secret', // 从Google控制台获取
  'http://localhost:3000/auth/callback' // 需与Google控制台配置的重定向URI一致
);

// 接收前端传来的授权码
app.post('/auth/google/code', async (req, res) => {
  try {
    const { code } = req.body;
    // 用授权码交换Google的access_token和id_token
    const { tokens } = await client.getToken(code);
    client.setCredentials(tokens);

    // 获取用户基本信息
    const userInfoRes = await client.request({
      url: 'https://www.googleapis.com/oauth2/v3/userinfo'
    });
    const userData = userInfoRes.data;

    // 复用你现有Passport的用户逻辑:查找/创建用户,完成登录
    const user = await findOrCreateUser(userData); // 替换成你自己的数据库操作

    // 若使用session认证,通过Passport的req.login创建会话
    req.login(user, (err) => {
      if (err) throw err;
      return res.json({ success: true, user: userData });
    });

    // 若使用JWT,生成token返回给前端:
    // const token = generateJwtToken(user); // 替换成你的JWT生成逻辑
    // return res.json({ success: true, token, user: userData });
  } catch (err) {
    console.error('认证失败:', err);
    res.status(401).json({ success: false, message: '授权码无效或已过期' });
  }
});

2. 前端实现授权码发送逻辑

在Vue组件中实现sendCodeToBackend函数,把授权码POST到后端新增的接口:

方案一:使用原生fetch

const sendCodeToBackend = async (code) => {
  try {
    const res = await fetch('http://localhost:3000/auth/google/code', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code }),
      credentials: 'include' // 若后端用session认证,需携带cookie
    });

    const data = await res.json();
    if (data.success) {
      console.log('登录成功:', data.user);
      // 跳转到受保护页面
      window.location.href = '/protected';
    } else {
      alert('登录失败,请重试');
    }
  } catch (err) {
    console.error('请求出错:', err);
    alert('网络异常,请稍后重试');
  }
};

方案二:使用axios(需先安装axios)

import axios from 'axios';

const sendCodeToBackend = async (code) => {
  try {
    const res = await axios.post('http://localhost:3000/auth/google/code', { code }, {
      withCredentials: true // 携带session cookie
    });

    if (res.data.success) {
      console.log('登录成功:', res.data.user);
      window.location.href = '/protected';
    }
  } catch (err) {
    console.error('登录失败:', err);
    alert('登录失败,请重试');
  }
};

然后在Google授权回调中调用这个函数:

callback: (response) => {
  console.log("授权响应:", response);
  if (response.code) {
    sendCodeToBackend(response.code);
  }
}

关键注意事项

  • Google控制台配置:确保你的OAuth 2.0客户端ID已添加:
    • 已授权的JavaScript来源:填写你的前端域名(如http://localhost:5173)
    • 授权重定向URI:填写后端配置的redirect_uri(如http://localhost:3000/auth/callback)
  • 跨域问题:若前后端端口不同,后端需配置CORS:
const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:5173', // 你的前端地址
  credentials: true
}));
  • 授权码有效期:Google授权码仅5分钟有效,且只能使用一次,需确保及时发送到后端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:17:48