Passport.js配置Google OAuth2.0授权后无法获取性别生日等信息如何解决
问题原因
你遇到的问题核心是两个配置缺失:
- 谷歌的基础OAuth2用户信息接口默认只返回邮箱、头像、昵称等基础公开信息,性别、生日、地址属于敏感字段,需要调用Google People API才能获取,你没有配置Passport策略从People API拉取用户信息
- 大概率你还没有在Google Cloud控制台启用Google People API,就算scope配置正确也无法拉取对应数据
解决步骤
1. 前置配置检查
- 打开Google Cloud控制台,进入「API和服务」-「启用API和服务」,搜索
Google People API并启用 - 确认OAuth同意屏幕中你添加的三个scope状态为「已批准」,如果是测试模式,确保你测试用的谷歌账号在「测试用户」列表中
- 测试用的谷歌账号需要已经在账号设置中填写了性别、出生日期、地址信息,否则对应字段会返回空值
2. 修改Passport策略配置
修改你的GoogleStrategy初始化参数,添加userProfileURL配置,指定从People API拉取你需要的字段:
passport.use( new GoogleStrategy( { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: GOOGLE_CALLBACK_URL, passReqToCallback: true, // 新增配置:指定从People API拉取用户信息,按需填写你需要的字段 userProfileURL: "https://people.googleapis.com/v1/people/me?personFields=genders,birthdays,addresses,emailAddresses,names,photos" }, async (req, accessToken, refreshToken, profile, cb) => { // 对应字段会存在profile._json中,直接读取即可 console.log("性别:", profile._json.genders?.[0]?.value) console.log("出生日期:", profile._json.birthdays?.[0]?.date) console.log("地址:", profile._json.addresses?.[0]?.formattedValue) // 原有业务逻辑不变 } )
3. 可选方案:主动调用People API
如果你不想修改Passport的默认配置,也可以在回调函数中用拿到的accessToken主动请求People API获取字段:
const fetch = require('node-fetch') // 回调函数内逻辑 async (req, accessToken, refreshToken, profile, cb) => { const peopleRes = await fetch( "https://people.googleapis.com/v1/people/me?personFields=genders,birthdays,addresses", { headers: { Authorization: `Bearer ${accessToken}` } } ) const peopleInfo = await peopleRes.json() console.log(peopleInfo) // 后续业务逻辑 }
测试注意
修改配置后请用浏览器隐私模式测试,避免之前的授权缓存没有更新scope,导致还是拉取不到新字段。
内容的提问来源于stack exchange,提问作者Olcay
相关产品推荐
相关产品推荐

