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

使用NextAuth集成Google Provider时遭遇‘acces denied’错误求助

NextAuth 集成 Google Provider 出现「Access Denied」问题

问题描述

  • 触发场景:使用NextAuth通过Google账户登录,选择账户并确认后弹出「Access Denied」提示
    错误提示截图
  • 已完成配置:
    • 授权重定向URI设置为 http://localhost:3001/api/auth/callback/google
    • 项目运行在 http://localhost:3001 端口,采用OAuth协议
    • 已添加2个Google账户作为测试用户
  • 相关NextAuth配置代码:
const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    })
  ],
  callbacks: {
    async session({ session }) {
      // store the user id from MongoDB to session
      const sessionUser = await User.findOne({ email: session.user.email });
      session.user.id = sessionUser._id.toString();

      return session;
    },
    async signIn({ profile }) {
      try {
        await connectToDB();

        // check if user already exists
        const userExists = await User.findOne({ email: profile.email });

        // if not, create a new document and save user in MongoDB
        if (!userExists) {
          await User.create({
            email: profile.email,
            username: profile.name.replace(" ", "").toLowerCase(),
            image: profile.picture,
          });
        }

        return true
      } catch (error) {
        console.log("Error checking if user exists: ", error.message);
        return false
      }
    },
  }
})

export { handler as GET, handler as POST }

排查与解决方案

1. 核对Google Cloud Console OAuth配置

  • 重定向URI完全匹配:确认配置的URI和项目实际回调地址完全一致,包括协议(http/https)、端口、路径,不能有多余的斜杠或空格
  • 客户端类型正确:本地开发场景下,OAuth客户端类型需选择「Web应用」,而非「桌面应用」或其他类型
  • 测试用户有效性:确保添加的测试用户邮箱与实际登录的Google账户邮箱完全一致,无拼写错误

2. 验证环境变量正确性

  • 检查GOOGLE_ID和GOOGLE_CLIENT_SECRET是否完整复制自Google Cloud Console,避免包含空格、换行符等无效字符
  • 临时在代码中打印console.log(process.env.GOOGLE_ID),确认环境变量是否被正确加载

3. 排查signIn回调逻辑

  • 你的signIn回调中,任何异常都会返回false,直接导致登录被拒绝:
    • 确认connectToDB()函数的MongoDB连接字符串配置正确,数据库服务正常运行
    • 检查User模型定义是否正确,字段(如email、username)与创建逻辑匹配
    • 可临时注释数据库操作逻辑,仅返回true测试基础登录流程,判断是否为数据库逻辑导致的问题(示例代码如下)
const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    })
  ],
  callbacks: {
    async session({ session }) {
      // 临时注释数据库逻辑,测试基础登录
      // const sessionUser = await User.findOne({ email: session.user.email });
      // session.user.id = sessionUser._id.toString();

      return session;
    },
    async signIn({ profile }) {
      try {
        // 临时注释数据库操作,仅返回true
        // await connectToDB();
        // const userExists = await User.findOne({ email: profile.email });
        // if (!userExists) {
        //   await User.create({
        //     email: profile.email,
        //     username: profile.name.replace(" ", "").toLowerCase(),
        //     image: profile.picture,
        //   });
        // }
        return true
      } catch (error) {
        console.log("Error checking if user exists: ", error.message);
        return false
      }
    },
  }
})

export { handler as GET, handler as POST }

4. 检查版本兼容性

确保next-auth与@next-auth/google-provider的版本匹配,避免因版本不兼容导致的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:37:08