憑證供應商
憑證供應商可讓您處理使用任意憑證登入,例如使用者名稱和密碼、網域、雙因素驗證或硬體裝置(例如 YubiKey U2F / FIDO)。
其目的是支援您需要驗證使用者身分的現有系統的使用案例,因此以這種方式驗證的使用者不會儲存在資料庫中。
資源
設定
/auth.ts
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
export const { signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
credentials: {
username: { label: "Username" },
password: { label: "Password", type: "password" },
},
async authorize({ request }) {
const response = await fetch(request)
if (!response.ok) return null
return (await response.json()) ?? null
},
}),
],
})
自訂錯誤訊息
您可以在 authorize
函式中擲回自訂錯誤,以將自訂錯誤訊息傳回給使用者。
@/auth.ts
import NextAuth, { CredentialsSignin } from "next-auth"
import Credentials from "next-auth/providers/credentials"
class InvalidLoginError extends CredentialsSignin {
code = "Invalid identifier or password"
}
export const { handlers, auth } = NextAuth({
providers: [
Credentials({
credentials: {
username: { label: "Username" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
throw new InvalidLoginError()
},
}),
],
})
然後,您將在使用者登入嘗試失敗後返回的登入頁面的查詢參數中收到該自訂錯誤碼,例如 https://app.company.com/auth/signin?error=CredentialsSignin&code=Invalid+identifier+or+password
。
⚠️
OAuth 供應商投入大量金錢、時間和工程精力來建構
- 濫用偵測(機器人防護、速率限制)
- 密碼管理(密碼重設、憑證填充、輪換)
- 資料安全性(加密/加鹽、強度驗證)
以及更多身分驗證解決方案。您的應用程式很可能會受益於利用這些久經考驗的解決方案,而不是嘗試從頭開始重建它們。
如果您仍然想為您的應用程式建構基於密碼的身分驗證,儘管存在這些風險,Auth.js 仍讓您可以完全控制這樣做。