如何在Postman中测试基于Passport的Google OAuth2后端认证API?
如何用Postman测试基于Passport的Google OAuth2认证后端
前提准备
- 修正代码关键配置
- 将
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)); }
- 将
- 启动本地服务,确认控制台输出
Server starting on port {{你的端口}}
Postman测试步骤
方法一:使用Postman内置OAuth2授权流程
- 新建GET请求,URL填写
http://localhost:{{你的端口}}/auth/google - 切换到Authorization标签页,授权类型选择
OAuth 2.0 - 点击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
- 点击Request Token,弹出Google登录页面后完成登录授权,Postman会自动获取访问令牌
- 点击Use Token,发送请求,可在
/auth/google/callback的处理函数中临时添加res.json(req.user),方便验证是否成功获取用户信息
方法二:手动模拟授权流程
- 在浏览器中访问
http://localhost:{{你的端口}}/auth/google,完成Google登录授权后,浏览器会跳转到callbackURL,此时地址栏会包含code参数 - 复制该
code值,在Postman中新建POST请求,URL填写https://oauth2.googleapis.com/token - 切换到Body标签页,选择
form-data,添加以下键值对:- grant_type:
authorization_code - code:刚才复制的授权码
- client_id:你的Google客户端ID
- client_secret:你的Google客户端密钥
- redirect_uri:和代码一致的
callbackURL
- grant_type:
- 发送请求,成功后会返回包含
access_token的响应,可使用该令牌验证后端接口的权限逻辑
内容的提问来源于stack exchange,提问作者Routfin
相关产品推荐
相关产品推荐

