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

Forward Email 提供者

概觀

Forward Email 提供者使用電子郵件傳送「魔法連結」,其中包含帶有驗證權杖的 URL,可用於登入。

除了提供一個或多個 OAuth 服務外,新增透過電子郵件登入的支援,讓使用者在無法存取其 OAuth 帳戶時(例如,如果帳戶被鎖定或刪除)仍能登入。

Forward Email 提供者可以與一個或多個 OAuth 提供者結合使用(或取代)。

運作方式

在初始登入時,會將一個驗證權杖傳送到提供的電子郵件地址。預設情況下,此權杖的有效時間為 24 小時。如果驗證權杖在該時間內被使用(即點擊電子郵件中的連結),則會為使用者建立帳戶,並將其登入。

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

⚠️

Forward Email 提供者可以與 BasicAuth 和資料庫管理的工作階段一起使用,但是您必須設定一個資料庫才能使用它。不使用資料庫無法啟用電子郵件登入。

組態

  1. 首先,您需要將您的網域新增至您的 Forward Email 帳戶。Forward Email 需要這樣做,並且您在 from 提供者選項中使用的地址網域必須與您加入的網域相同。

  2. 接下來,您必須在我的帳戶 → 安全性中產生 API 金鑰。您可以將此 API 金鑰儲存為 AUTH_FORWARDEMAIL_KEY 環境變數。

AUTH_FORWARDEMAIL_KEY=abc

如果您將您的環境變數命名為 AUTH_FORWARDEMAIL_KEY,提供者會自動擷取它,您的 Auth.js 組態物件可以更簡單。但是,如果您想將其重新命名為其他名稱,您必須在 Auth.js 組態中手動將其傳遞至提供者。

./auth.ts
import NextAuth from "next-auth"
import ForwardEmail from "next-auth/providers/forwardemail"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: ...,
  providers: [
    ForwardEmail({
      // If your environment variable is named differently than default
      apiKey: AUTH_FORWARDEMAIL_KEY,
      from: "no-reply@company.com"
    }),
  ],
})
  1. 不要忘記設定其中一個資料庫轉接器,以儲存電子郵件驗證權杖。

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

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

自訂

電子郵件內文

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

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

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

./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.forwardemail.net/v1/emails", {
    method: "POST",
    headers: {
      Authorization: `Basic ${btoa(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("Forward Email 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 ForwardEmail from "next-auth/providers/forwardemail"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    ForwardEmail({
      async generateVerificationToken() {
        return crypto.randomUUID()
      },
    }),
  ],
})

正規化電子郵件地址

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

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