>使用nextauth.js和next.js安全地管理用戶訪問:基於憑證的身份驗證指南
可靠的身份驗證是控制對Web應用程序的訪問的最重要的。儘管OAuth提供商(例如Google或Github)很受歡迎,但電子郵件/密碼身份驗證仍然是一個普遍且安全的選擇。本指南詳細詳細介紹了使用功能強大的NextAuth.js庫在Next.js應用程序中實現基於憑據的身份驗證。 我們將逐步分解該過程,以便在您自己的項目中輕鬆實現。
了解NextAuth.js及其憑證提供商nextAuth.js憑據提供者提供:
>步驟1:使用憑據提供商配置NextAuth.js
步驟2:創建身份驗證API路由NextAuthOptions
<code class="language-javascript">import { NextAuthOptions } from "next-auth"; import CredentialProvider from "next-auth/providers/credentials"; import bcrypt from "bcryptjs"; import { dbConnect } from "@/lib/dbConnect"; import UserModel from "@/model/User"; export const authOptions: NextAuthOptions = { providers: [ CredentialProvider({ id: "credentials", name: "Credentials", credentials: { email: { label: "Email", type: "text" }, password: { label: "Password", type: "password" }, }, async authorize(credentials: any): Promise<any> { await dbConnect(); try { const user = await UserModel.findOne({ $or: [ { email: credentials.identifier }, { username: credentials.identifier }, ], }); if (!user) { throw new Error("Invalid email or username"); } if (!user.isVerified) { throw new Error("Please verify your account."); } const isPasswordCorrect = await bcrypt.compare(credentials.password, user.password); if (isPasswordCorrect) { return user; } else { throw new Error("Incorrect password."); } } catch (err: any) { throw new Error(err.message); //Improved error handling } }, }), ], callbacks: { async jwt({ token, user }) { if (user) { token._id = user._id?.toString(); token.isVerified = user?.isVerified; token.username = user?.username; token.isAcceptingMessages = user?.isAcceptingMessages; } return token; }, async session({ session, token }) { if (token) { session.user._id = token._id?.toString(); session.user.isVerified = token?.isVerified; session.user.username = token?.username; session.user.isAcceptingMessages = token?.isAcceptingMessages; } return session; }, }, pages: { signIn: "/sign-in", error: "/sign-in", }, session: { strategy: "jwt", }, secret: process.env.NEXTAUTH_SECRET, };</code>
<code class="language-javascript">// app/api/auth/[...nextauth]/route.ts import NextAuth from "next-auth"; import { authOptions } from "@/lib/authOptions"; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };</code>
保持組織良好的項目結構:
步驟4:在Next.js 13(App Router)中處理路線
API路由的提供的代碼段已經正確配置為Next.js 13使用應用程序路由器。<code>/lib /authOptions.ts /model /User.ts /app /api /auth /[...nextauth]/route.ts</code>
該全面的指南使您使用nextauth.js在您的下一個項目中實現了安全的基於憑證的身份驗證。 憑證提供商的靈活性允許對身份驗證流的完全控制,從而確保了穩健而安全的用戶體驗。請記住將數據庫連接(
和以上是在Next.js中使用NextAuth.js實施基於憑證的身份驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!