コンテンツへスキップ
NextAuth.js v4 からの移行ですか? 移行ガイドをご覧ください.

Google プロバイダー

リソース

セットアップ

コールバックURL

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 and Team -2024