コンテンツへスキップ
NextAuth.js v4からの移行? 参照 移行ガイド.

Mailgunプロバイダー

リソース

概要

Mailgunプロバイダーは、検証トークンを含むURLを格納した「マジックリンク」を送信するためにメールを使用します。

1つ以上のOAuthサービスに加えてメールによるサインインのサポートを追加すると、OAuthアカウントへのアクセスを失った場合(例:アカウントがロックまたは削除された場合)にユーザーがサインインする方法が提供されます。

Mailgunプロバイダーは、1つ以上のOAuthプロバイダーと組み合わせて(または代わりに)使用できます。

動作方法

最初のサインイン時に、**検証トークン**が指定されたメールアドレスに送信されます。デフォルトでは、このトークンは24時間有効です。その時間内に検証トークンが使用された場合(つまり、メール内のリンクをクリックした場合)、ユーザーのアカウントが作成され、サインインされます。

サインイン時に既存アカウントのメールアドレスが提供された場合、メールが送信され、メール内のリンクをクリックすると、そのメールアドレスに関連付けられたアカウントにサインインされます。

⚠️

Mailgunプロバイダーは、JSON Webトークンとデータベース管理セッションの両方で使用できますが、**データベースを設定する必要があります**。データベースを使用せずにメールサインインを有効にすることはできません。

設定

  1. まず、ドメインをMailgunアカウントに追加する必要があります。これはMailgunで必須であり、fromプロバイダーオプションで使用されるアドレスのドメインです。

  2. 次に、Mailgun設定でAPIキーを生成する必要があります。AUTH_MAILGUN_KEY環境変数としてこのAPIキーを保存できます。

AUTH_MAILGUN_KEY=abc

環境変数の名前をAUTH_MAILGUN_KEYにした場合、プロバイダーは自動的にそれを取得し、Auth.jsの設定オブジェクトを簡素化できます。ただし、別の名前に変更する場合は、Auth.jsの設定でプロバイダーに手動で渡す必要があります。

./auth.ts
import NextAuth from "next-auth"
import Mailgun from "next-auth/providers/mailgun"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: ...,
  providers: [
    Mailgun({
      // If your environment variable is named differently than default
      apiKey: import.meta.env.AUTH_MAILGUN_KEY,
      from: "no-reply@company.com"
    }),
  ],
})
  1. メール検証トークンを保存するために、データベースアダプターの1つを設定することを忘れないでください。

  2. これで、/api/auth/signinでメールアドレスを使用してサインインプロセスを開始できます。

ユーザーアカウント(つまり、Usersテーブルのエントリ)は、初めてメールアドレスを検証するまで作成されません。メールアドレスが既にアカウントに関連付けられている場合、ユーザーはマジックリンクメール内のリンクをクリックして検証トークンを使用すると、そのアカウントにサインインされます。

カスタマイズ

メール本文

Mailgun()にカスタム関数としてsendVerificationRequestオプションを渡すことで、送信されるサインインメールを完全にカスタマイズできます。

./auth.ts
import NextAuth from "next-auth"
import Mailgun from "next-auth/providers/mailgun"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Mailgun({
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
      sendVerificationRequest({
        identifier: email,
        url,
        provider: { server, from },
      }) {
        // your function
      },
    }),
  ],
})

例として、以下に組み込みのsendVerificationRequest()メソッドのソースを示します。ここで、HTML(html())をレンダリングし、ネットワーク呼び出し(fetch())をMailgunに行い、実際に送信を行っていることに注意してください。

./lib/authSendRequest.ts
export async function sendVerificationRequest(params) {
  const { identifier: to, provider, url, theme } = params
  const { host } = new URL(url)
  const domain = provider.from.split("@").at(1)
 
  if (!domain) throw new Error("malformed Mailgun domain")
 
  const form = new FormData()
  form.append("from", `${provider.name} <${provider.from}>`)
  form.append("to", to)
  form.append("subject", `Sign in to ${host}`)
  form.append("html", html({ host, url, theme }))
  form.append("text", text({ host, url }))
 
  const res = await fetch(`https://api.mailgun.net/v3/${domain}/messages`, {
    method: "POST",
    headers: {
      Authorization: `Basic ${btoa(`api:${provider.apiKey}`)}`,
    },
    body: form,
  })
 
  if (!res.ok) throw new Error("Mailgun error: " + (await res.text()))
}
 
function html(params: { url: string; host: string; theme: Theme }) {
  const { url, host, theme } = params
 
  const escapedHost = host.replace(/\./g, "&#8203;.")
 
  const brandColor = theme.brandColor || "#346df1"
  const color = {
    background: "#f9f9f9",
    text: "#444",
    mainBackground: "#fff",
    buttonBackground: brandColor,
    buttonBorder: brandColor,
    buttonText: theme.buttonText || "#fff",
  }
 
  return `
<body style="background: ${color.background};">
  <table width="100%" border="0" cellspacing="20" cellpadding="0"
    style="background: ${color.mainBackground}; max-width: 600px; margin: auto; border-radius: 10px;">
    <tr>
      <td align="center"
        style="padding: 10px 0px; font-size: 22px; font-family: Helvetica, Arial, sans-serif; color: ${color.text};">
        Sign in to <strong>${escapedHost}</strong>
      </td>
    </tr>
    <tr>
      <td align="center" style="padding: 20px 0;">
        <table border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td align="center" style="border-radius: 5px;" bgcolor="${color.buttonBackground}"><a href="${url}"
                target="_blank"
                style="font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${color.buttonText}; text-decoration: none; border-radius: 5px; padding: 10px 20px; border: 1px solid ${color.buttonBorder}; display: inline-block; font-weight: bold;">Sign
                in</a></td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td align="center"
        style="padding: 0px 0px 10px 0px; font-size: 16px; line-height: 22px; font-family: Helvetica, Arial, sans-serif; color: ${color.text};">
        If you did not request this email you can safely ignore it.
      </td>
    </tr>
  </table>
</body>
`
}
 
// Email Text body (fallback for email clients that don't render HTML, e.g. feature phones)
function text({ url, host }: { url: string; host: string }) {
  return `Sign in to ${host}\n${url}\n\n`
}

多くのメールクライアントと互換性のあるReactを使用して見栄えの良いメールを生成したい場合は、mjmlまたはreact-emailを確認してください。

検証トークン

デフォルトでは、ランダムな検証トークンを生成しています。上書きしたい場合は、プロバイダーオプションでgenerateVerificationTokenメソッドを定義できます。

./auth.ts
import NextAuth from "next-auth"
import Mailgun from "next-auth/providers/mailgun"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Mailgun({
      async generateVerificationToken() {
        return crypto.randomUUID()
      },
    }),
  ],
})

メールアドレスの正規化

デフォルトでは、Auth.jsはメールアドレスを正規化します。アドレスを大文字と小文字を区別しないものとして扱い(技術的にはRFC 2821仕様に準拠していませんが、実際には問題を解決するよりも多くの問題を引き起こします。つまり、データベースからメールでユーザーを検索する場合です。)コンマ区切りで渡された可能性のあるセカンダリーメールアドレスも削除します。MailgunプロバイダーのnormalizeIdentifierメソッドを使用して独自の正規化を適用できます。次の例はデフォルトの動作を示しています。

./auth.ts
import NextAuth from "next-auth"
import Mailgun from "next-auth/providers/mailgun"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Mailgun({
      normalizeIdentifier(identifier: string): string {
        // Get the first two elements only,
        // separated by `@` from user input.
        let [local, domain] = identifier.toLowerCase().trim().split("@")
        // The part before "@" can contain a ","
        // but we remove it on the domain part
        domain = domain.split(",")[0]
        return `${local}@${domain}`
 
        // You can also throw an error, which will redirect the user
        // to the sign-in page with error=EmailSignin in the URL
        // if (identifier.split("@").length > 2) {
        //   throw new Error("Only one email allowed")
        // }
      },
    }),
  ],
})
⚠️

複数渡された場合でも、常に単一のメールアドレスを返すようにしてください。

Auth.js © Balázs Orbán and Team -2024