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

Nodemailer 供應商

概觀

Nodemailer 供應商使用電子郵件傳送包含驗證權杖 URL 的「魔法連結」,可用於登入。

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

Nodemailer 供應商可以與一或多個 OAuth 供應商一起使用(或取代)。

運作方式

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

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

⚠️

Nodemailer 供應商可以與 JSON Web Token 和資料庫管理的工作階段一起使用,但是您必須設定資料庫才能使用它。如果不使用資料庫,則無法啟用電子郵件登入。

設定

  1. Auth.js 不包含 nodemailer 作為依賴項,因此如果您想要使用 Nodemailer 供應商,則需要自行安裝。
npm install nodemailer
  1. 您將需要一個 SMTP 帳戶;理想情況下,是為 已知可與 nodemailer 搭配使用的服務 之一。Nodemailer 也適用於其他傳輸方式,但是如果您想要使用基於 HTTP 的電子郵件服務,我們建議您使用專為這些服務設計的其他 Auth.js 供應商,例如 ResendSendgrid

  2. 有兩種方式可以設定 SMTP 伺服器連線。

您可以使用連線字串或 nodemailer 設定物件。

.env
EMAIL_SERVER=smtp://username:password@smtp.example.com:587
EMAIL_FROM=noreply@example.com
./auth.ts
import NextAuth from "next-auth"
import Nodemailer from "next-auth/providers/nodemailer"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: ...,
  providers: [
    Nodemailer({
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
    }),
  ],
})
  1. 請勿忘記設定其中一個資料庫轉接器,以儲存電子郵件驗證權杖。

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

在使用者第一次驗證其電子郵件地址之前,不會為該使用者建立使用者帳戶(即 Users 表格中的條目)。如果電子郵件地址已經與帳戶關聯,則使用者在使用電子郵件中的連結時,將登入該帳戶。

自訂

電子郵件內文

您可以完全自訂傳送的登入電子郵件,方法是將自訂函數作為 sendVerificationRequest 選項傳遞給 Nodemailer()

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

例如,以下顯示了我們內建的 sendVerificationRequest() 方法的來源。請注意,我們正在此方法中呈現 HTML (html()) 並進行網路呼叫 (transport.sendMail()) 以實際將電子郵件傳送到電子郵件供應商。

import { createTransport } from "nodemailer"
 
export async function sendVerificationRequest(params) {
  const { identifier, url, provider, theme } = params
  const { host } = new URL(url)
  // NOTE: You are not required to use `nodemailer`, use whatever you want.
  const transport = createTransport(provider.server)
  const result = await transport.sendMail({
    to: identifier,
    from: provider.from,
    subject: `Sign in to ${host}`,
    text: text({ url, host }),
    html: html({ url, host, theme }),
  })
  const failed = result.rejected.concat(result.pending).filter(Boolean)
  if (failed.length) {
    throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`)
  }
}
 
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 Nodemailer from "next-auth/providers/nodemailer"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Nodemailer({
      async generateVerificationToken() {
        return crypto.randomUUID()
      },
    }),
  ],
})

正規化電子郵件地址

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

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