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

Sendgrid プロバイダー

概要

Sendgridプロバイダーは、認証トークンを含むURLが記載された「マジックリンク」を送信するためにメールを使用します。これを使ってサインインできます。

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

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

仕組み

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

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

⚠️

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

設定

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

  2. 次に、SendgridダッシュボードでAPIキーを生成する必要があります。このAPIキーを環境変数AUTH_SENDGRID_KEYとして保存できます。

AUTH_SENDGRID_KEY=abc

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

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

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

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

カスタマイズ

メール本文

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

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

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

./lib/authSendRequest.ts
export async function sendVerificationRequest(params) {
  const { identifier: to, provider, url, theme } = params
  const { host } = new URL(url)
  const res = await fetch("https://api.sendgrid.com/v3/mail/send", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${provider.apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      personalizations: [{ to: [{ email: to }] }],
      from: { email: provider.from },
      subject: `Sign in to ${host}`,
      content: [
        { type: "text/plain", value: text({ url, host }) },
        { type: "text/html", value: html({ url, host, theme }) },
      ],
    }),
  })
 
  if (!res.ok) throw new Error("Sendgrid error: " + (await res.text()))
}
 
function html(params: { url: string; host: string; theme: Theme }) {
  const { url, host, theme } = params
 
  const escapedHost = host.replace(/\./g, "​.")
 
  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 Sendgrid from "next-auth/providers/sendgrid"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Sendgrid({
      async generateVerificationToken() {
        return crypto.randomUUID()
      },
    }),
  ],
})

メールアドレスの正規化

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

./auth.ts
import NextAuth from "next-auth"
import Sendgrid from "next-auth/providers/sendgrid"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Sendgrid({
      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