>使用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>>步骤3:项目文件结构(示例)
保持组织良好的项目结构:
步骤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中文网其他相关文章!