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

如何在Postman中测试基于Passport的Google OAuth2后端认证API?

如何用Postman测试基于Passport的Google OAuth2认证后端

前提准备

  1. 修正代码关键配置
    • 将callbackURL从http://www.example.com/auth/google/callback改为本地可访问地址,比如http://localhost:3000/auth/google/callback(替换3000为你实际使用的端口)
    • 登录Google Cloud控制台,在OAuth客户端设置里把上述callbackURL添加到授权重定向URI列表
    • 补充Passport必要的初始化代码(当前代码缺失这部分):
      app.use(passport.initialize());
      app.use(passport.session());
      
      // 序列化/反序列化用户(需结合你的User模型实现)
      passport.serializeUser((user, done) => done(null, user.id));
      passport.deserializeUser((id, done) => {
        User.findById(id, (err, user) => done(err, user));
      });
      
    • 实现User.findOrCreate逻辑:这是Passport文档的示例方法,实际要基于你使用的数据库编写用户查询或创建代码,比如用Mongoose的示例:
      // 导入你的User模型
      const User = require('./models/User');
      
      // 替换示例中的findOrCreate
      function(accessToken, refreshToken, profile, cb) {
        User.findOne({ googleId: profile.id })
          .then(existingUser => {
            if (existingUser) return cb(null, existingUser);
            // 创建新用户
            return new User({ googleId: profile.id, name: profile.displayName }).save();
          })
          .then(user => cb(null, user))
          .catch(err => cb(err));
      }
      
  2. 启动本地服务,确认控制台输出Server starting on port {{你的端口}}

Postman测试步骤

方法一:使用Postman内置OAuth2授权流程

  1. 新建GET请求,URL填写http://localhost:{{你的端口}}/auth/google
  2. 切换到Authorization标签页,授权类型选择OAuth 2.0
  3. 点击Get New Access Token,填写以下参数:
    • Token Name:自定义名称(如Google OAuth Test)
    • Grant Type:选择Authorization Code
    • Callback URL:填写和代码一致的http://localhost:3000/auth/google/callback
    • Auth URL:https://accounts.google.com/o/oauth2/v2/auth
    • Access Token URL:https://oauth2.googleapis.com/token
    • Client ID:你的Google OAuth客户端ID
    • Client Secret:你的Google OAuth客户端密钥
    • Scope:填写profile
  4. 点击Request Token,弹出Google登录页面后完成登录授权,Postman会自动获取访问令牌
  5. 点击Use Token,发送请求,可在/auth/google/callback的处理函数中临时添加res.json(req.user),方便验证是否成功获取用户信息

方法二:手动模拟授权流程

  1. 在浏览器中访问http://localhost:{{你的端口}}/auth/google,完成Google登录授权后,浏览器会跳转到callbackURL,此时地址栏会包含code参数
  2. 复制该code值,在Postman中新建POST请求,URL填写https://oauth2.googleapis.com/token
  3. 切换到Body标签页,选择form-data,添加以下键值对:
    • grant_type:authorization_code
    • code:刚才复制的授权码
    • client_id:你的Google客户端ID
    • client_secret:你的Google客户端密钥
    • redirect_uri:和代码一致的callbackURL
  4. 发送请求,成功后会返回包含access_token的响应,可使用该令牌验证后端接口的权限逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:46:07