You need to enable JavaScript to run this app. Google OAuth2登录验证持续失败,授权完成后自动跳转首页问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Google OAuth2登录验证持续失败,授权完成后自动跳转首页问题咨询

故障原因及修复方案

触发重定向到首页的直接原因是passport谷歌验证逻辑判定登录失败,走了failureRedirect: '/'的规则,问题出在GoogleStrategy的数据库操作配置:

  • 两个配置错误导致查询返回的用户为空:
    1. 未开启upsert: true:当前findOneAndUpdate只会匹配已存在的用户记录,新用户首次登录时不会自动插入新文档,查询结果为空
    2. 未配置返回更新后的文档:MongoDB的findOneAndUpdate默认返回更新前的文档,即使补全upsert配置,首次插入新用户时返回的user.value依然是null

修复后的代码

passport.use(new GoogleStrategy({
        clientID: 'GOOGLE-CLIENT-ID',
        clientSecret: 'GOOGLE-CLIENT-SECRET',
        callbackURL: "https://chat-roomproject.herokuapp.com/auth/google/callback"
      },
      function(accessToken, refreshToken, profile, cb) {
        myDataBase.findOneAndUpdate(
          { googleId: profile.id }, 
          {
            $setOnInsert: {
              googleId: profile.id,
              // 可按需补充其他用户字段,比如用户名、头像
              username: profile.displayName,
              avatar: profile.photos?.[0]?.value
            },
          },
          {
            upsert: true, // 开启新用户自动插入
            returnDocument: 'after' // 返回更新后的文档,旧版MongoDB驱动请使用returnNewDocument: true
          },
          function (err, result) {
            if (err) return cb(err);
            return cb(null, result.value);
          }
        );
      }
    ));

额外排查项

修复上述配置后仍有问题可检查:

  1. 确认express-session配置顺序正确,需放在passport初始化之前,session存储服务运行正常
  2. 确认Google Cloud后台配置的OAuth授权回调地址和代码中callbackURL完全一致,无协议、域名、路径差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:18:03