跳至內容
正在從 NextAuth.js v4 遷移嗎?請閱讀 我們的遷移指南.

Google 供應商

資源

設定

回調網址

https://example.com/api/auth/callback/google

環境變數

AUTH_GOOGLE_ID
AUTH_GOOGLE_SECRET

組態

@/auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [Google],
})

注意事項

刷新令牌

Google 僅在使用者首次登入時才向應用程式提供刷新令牌。

若要強制 Google 重新發出刷新令牌,使用者需要從其帳戶中移除該應用程式,然後再次登入: https://myaccount.google.com/permissions

或者,您也可以在 authorizationparams 物件中傳遞選項,這會強制在每次登入時都提供刷新令牌,但這會要求所有使用者在每次登入時確認他們是否希望授予您的應用程式存取權。

如果您需要存取 Google 帳戶的刷新令牌或存取令牌,而且您未使用資料庫來保留使用者帳戶,這可能是您需要做的事情。

app/api/auth/[...nextauth]/route.ts
import Google from "next-auth/providers/google"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google({
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],
})

有關交換代碼以取得存取令牌和刷新令牌的更多資訊,請參閱 Google OAuth 文件

電子郵件已驗證

Google 也會在 OAuth 設定檔中傳回 email_verified 布林值屬性。

您可以使用此屬性來限制對在特定網域中具有已驗證帳戶的人員的存取。

@/auth.ts
export const { handlers, auth, signIn, signOut } = NextAuth({
  callbacks: {
    async signIn({ account, profile }) {
      if (account.provider === "google") {
        return profile.email_verified && profile.email.endsWith("@example.com")
      }
      return true // Do different verification for other providers that don't have `email_verified`
    },
  },
})
Auth.js © Balázs Orbán 和團隊 -2024