如何实现 Gmail API 访问以通过 Auth.js(使用 Google OAuth)登录?

问题描述 投票:0回答:1

我有一个 Next.js 应用程序,用户当前可以通过 Google OAuth 登录(使用 Auth.js)。现在我想访问用户的 Gmail 收件箱,但如果我按照 Gmail API 文档操作,用户必须再次登录。我可以阻止这种情况吗?对于这个用例有一些好的教程吗?

next.js gmail next-auth
1个回答
0
投票

您的 auth.ts 文件应该与此类似。 Google 提供商应具有下面列出的所有配置以及应用程序所需的所有范围。此配置将使 Google 返回刷新令牌。使用 signIn 回调将刷新令牌存储在数据库中。有了用户的刷新令牌您的 Gmail API 密钥,您只需一个同意屏幕即可访问用户的 Gmail,其中包括登录和授权。

export default {
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  callbacks: {
    async signIn({ account, user }) {
      if (account?.access_token && account?.refresh_token) {
        await storeRefresh(account.refresh_token, account.providerAccountId);
      }

      return true;
    }
  },
  providers: [

    Google({
      clientId: process.env.AUTH_GOOGLE_ID,
      clientSecret: process.env.AUTH_GOOGLE_SECRET,
      authorization: {
        params: {
          access_type: "offline",
          prompt: "consent",
          response_type: "code",
          scope:
            "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/gmail.readonly",
            },
          },
        })
  ],
} satisfies NextAuthConfig;
© www.soinside.com 2019 - 2024. All rights reserved.