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

使用Passport集成Google OAuth 2.0时缺失邮箱信息问题求助

Google OAuth 2.0集成时邮箱字段缺失的排查方案

问题背景

基于Node.js v18.12.1和Express框架,通过Passport实现Google OAuth 2.0集成时,发现创建新用户时profile.emails为undefined,且返回的_json中无email字段。已在代码中配置scope: ["email","profile"],但问题依旧。

相关代码片段

passport.use(new googleAuth.Strategy({
        clientID: process.env.GOOGLE_CLIENT_ID!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
        callbackURL: "http://localhost:3000/auth/google/secrets",
        scope: ["email","profile"]
    },
    (accessToken: string, refreshToken: string, profile: googleAuth.Profile, cb: VerifyCallback) => {
        User.findOne({googleId: profile.id}, (err: CallbackError, user: PassportLocalModel<IUser>) => {
            if(err){
                return cb(err);
            }else if(user){
                return cb(err, user);
            }else{
                const user = new User({
                    email: profile.emails![0].value,
                    googleId: profile.id,
                });

                user.save((err: CallbackError) => {
                    if(err){
                        console.log(err);
                        cb(err);
                    }
                })
            }
        })
       
    }
));

返回的_json内容(信息已脱敏)

_json: {
    sub: <somestring>,
    name: <some name>,
    given_name: <some name>,
    family_name: <some name>,
    picture: <some url>,
    locale: 'en-GB'
  }

可能的原因及排查方向

  • Google账号本身无可用邮箱或邮箱未公开
    若用户的Google账号仅通过手机号注册,未关联邮箱;或者用户在Google账号设置中隐藏了邮箱地址,即使申请了email权限,Google也不会返回该字段。可尝试用一个明确关联公开邮箱的Google账号测试。

  • OAuth consent screen配置不完整

    1. 登录Google Cloud Console,进入OAuth consent screen页面,检查Scopes for Google APIs是否已添加../auth/userinfo.email和../auth/userinfo.profile——仅在代码中配置scope是不够的,控制台必须同步配置。
    2. 若应用处于Testing状态,只有添加到测试用户列表的账号才能返回完整字段。未加入测试列表的账号授权时,Google会限制敏感字段返回。
  • Passport策略的配置细节问题

    1. 若使用的是passport-google-oauth20包,需显式指定userProfileURL参数。默认端点可能不返回邮箱,可添加:
      userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
      
    2. 尝试使用完整的scope URL替代简写,将配置改为:
      scope: [
          "https://www.googleapis.com/auth/userinfo.email",
          "https://www.googleapis.com/auth/userinfo.profile"
      ]
      
  • 用户未授权邮箱权限
    用户在授权弹窗中可能仅同意了基础的profile权限,拒绝了邮箱访问请求。可检查授权弹窗是否正确展示了邮箱权限的申请提示,或在流程中强制要求该权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:40:44