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

Postmark 供應商

概觀

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

除了單一或多個 OAuth 服務之外,新增電子郵件登入支援,讓使用者在失去 OAuth 帳戶存取權(例如,如果帳戶被鎖定或刪除)時,也能登入。

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

運作方式

在首次登入時,系統會將**驗證 Token**傳送至提供的電子郵件地址。預設情況下,此 Token 有效期為 24 小時。如果在該時間內使用驗證 Token(即點擊電子郵件中的連結),則會為使用者建立帳戶,並讓他們登入。

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

⚠️

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

設定

  1. 首先,您需要將您的網域新增至您的 Postmark 帳戶。Postmark 要求必須執行此操作,而且您在 from 供應商選項中使用的位址網域也必須如此。

  2. 接下來,您必須在 Postmark 儀表板中產生 API 金鑰。您可以將此 API 金鑰儲存為 AUTH_POSTMARK_KEY 環境變數。

AUTH_POSTMARK_KEY=abc

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

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

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

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

自訂

電子郵件內文

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

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

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

./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.postmark.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("Postmark 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

驗證 Token

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

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

正規化電子郵件地址

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

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