跳到內容
從 NextAuth.js v4 遷移?請閱讀 我們的遷移指南.

Resend 供應商

概述

Resend 供應商使用電子郵件發送「魔法連結」,其中包含帶有驗證令牌的 URL,可用於登入。

除了使用一個或多個 OAuth 服務登入之外,新增對透過電子郵件登入的支持,為使用者提供了一種方式,在他們無法存取 OAuth 帳戶時(例如,如果帳戶被鎖定或刪除)仍然可以登入。

Resend 供應商可以與一個或多個 OAuth 供應商結合使用(或替代)。

運作方式

在首次登入時,會將**驗證令牌**發送到提供的電子郵件地址。預設情況下,此令牌有效期為 24 小時。如果在此時間內使用驗證令牌(即,透過點擊電子郵件中的連結),則會為使用者建立一個帳戶,並且他們會登入。

如果有人在登入時提供了*現有帳戶*的電子郵件地址,則會發送一封電子郵件,並且當他們點擊電子郵件中的連結時,他們會登入與該電子郵件地址關聯的帳戶。

⚠️

Resend 供應商可以與 JSON Web Token 和資料庫管理的會話一起使用,但是**您必須設定一個資料庫**才能使用它。如果沒有使用資料庫,則無法啟用電子郵件登入。

組態

  1. 首先,您需要將您的網域新增到您的 Resend 帳戶。這是 Resend 的要求,而且這個網域是您在 from 供應商選項中使用的地址的網域。

  2. 接下來,您必須在Resend 儀表板中產生一個 API 金鑰。您可以將這個 API 金鑰儲存為 AUTH_RESEND_KEY 環境變數。

AUTH_RESEND_KEY=abc

如果您將環境變數命名為 AUTH_RESEND_KEY,則供應商會自動選取它,而且您的 Auth.js 組態物件可以更簡單。但是,如果您想將其重新命名為其他名稱,則必須在 Auth.js 組態中手動將其傳遞給供應商。

./auth.ts
import NextAuth from "next-auth"
import Resend from "next-auth/providers/resend"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: ...,
  providers: [
    Resend({
      // If your environment variable is named differently than default
      apiKey: AUTH_RESEND_KEY,
      from: "no-reply@company.com"
    }),
  ],
})
  1. 不要忘記設定一個資料庫適配器來儲存電子郵件驗證令牌。

  2. 您現在可以使用 /api/auth/signin 中的電子郵件地址開始登入程序。

使用者帳戶(即 Users 表格中的一個條目)在使用者第一次驗證其電子郵件地址之前不會建立。如果電子郵件地址已經與帳戶關聯,則當使用者點擊魔法連結電子郵件中的連結並使用完驗證令牌時,他們將登入該帳戶。

自訂

電子郵件內文

您可以透過將自訂函式作為 sendVerificationRequest 選項傳遞給 Resend(),完全自訂發送的登入電子郵件。

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

例如,以下顯示了我們的內建 sendVerificationRequest() 方法的原始碼。請注意,我們正在這裡的此方法中呈現 HTML (html()) 並進行網路呼叫 (fetch()) 以實際傳送到 Resend。

./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.resend.com/emails", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${provider.apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: provider.from,
      to,
      subject: `Sign in to ${host}`,
      html: html({ url, host, theme }),
      text: text({ url, host }),
    }),
  })
 
  if (!res.ok)
    throw new Error("Resend error: " + JSON.stringify(await res.json()))
}
 
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 來產生美觀的電子郵件,請查看 mjmlreact-email

驗證令牌

預設情況下,我們正在產生一個隨機驗證令牌。如果您想覆蓋它,可以在您的供應商選項中定義一個 generateVerificationToken 方法

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

正規化電子郵件地址

預設情況下,Auth.js 會正規化電子郵件地址。它將該地址視為不區分大小寫(這在技術上不符合 RFC 2821 規範,但在實踐中,這會導致比解決更多問題,即從資料庫中按電子郵件查詢使用者時)。它也會移除任何可能作為逗號分隔列表傳入的次要電子郵件地址。您可以透過 Resend 供應商上的 normalizeIdentifier 方法來應用您自己的正規化。以下範例顯示預設行為

./auth.ts
import NextAuth from "next-auth"
import Resend from "next-auth/providers/resend"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Resend({
      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 和團隊 -2024