NextJS鉴权方案: Next-Auth
XiaoYu
在 Next.js 应用中实现安全、灵活的登录系统,NextAuth.js 是一种常用选择。本文示例按 NextAuth.js v4 的 API 编写,其他主要版本的配置方式可能不同。
特点包括:
-
支持多种登录方式(OAuth、Credentials、Email 等)
-
支持 JWT 会话及配合适配器使用的数据库会话
-
简单集成,适配 Next.js App Router (/app) 新架构
-
安全加密,提供会话保护机制
基本安装与配置
js
npm install next-auth
在 /app/api/auth/[...nextauth]/route.ts 新建 API 路由,配置登录逻辑:
js
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import prisma from "@/lib/prisma"; // 你的数据库实例
import { compare } from "bcryptjs";
export const authOptions = {
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials.password) {
throw new Error("缺少邮箱或密码");
}
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});
if (!user || !(await compare(credentials.password, user.password))) {
throw new Error("邮箱或密码错误");
}
return { id: String(user.id), name: user.name, email: user.email };
},
}),
],
session: { strategy: "jwt" as const },
secret: {你的配置},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
}
return session;
},
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
必须配置的环境变量
在 .env 文件中添加:
js
地址=http://localhost:3000
名称=你的超长随机密钥
生成 NEXTAUTH_SECRET 建议用:
bash
openssl rand -base64 32
客户端登录使用
前端页面使用 signIn 方法进行登录:
js
'use client';
import { signIn } from "next-auth/react";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
const res = await signIn("credentials", {
email,
password,
redirect: false,
});
if (res?.error) {
setError(res.error);
} else {
router.push("/");
}
}
return (
<form onSubmit={handleSubmit}>
{/* 输入框省略 */}
<button type="submit">登录</button>
</form>
);
}
页面级权限控制(Server 端)
有些页面需要登录才能访问,可以封装 requireAuth:
js
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
export async function requireAuth() {
const session = await getServerSession(authOptions);
if (!session) {
throw new Error("未登录,禁止访问!");
}
return session;
}
在页面中调用:
js
import { requireAuth } from "@/lib/auth";
export default async function ProtectedPage() {
const session = await requireAuth();
return <div>欢迎回来,{session.user?.name}</div>;
}
API 级权限保护
如果是接口请求 API,也可以用类似方式:
js
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "未登录" }, { status: 401 });
}
return NextResponse.json({ message: "API调用成功" });
}
常见问题
1. 登录后访问 API 提示 JWT_SESSION_ERROR?
- 检查 NEXTAUTH_SECRET 是否一致
- 检查 Cookie 是否被篡改
- 本地开发可尝试清除 Cookie 重登
2. 前端怎么知道是否登录?
在客户端直接用 useSession():
js
import { useSession } from "next-auth/react";
const { data: session, status } = useSession();
-
status === "authenticated":已登录
-
status === "unauthenticated":未登录
灵活且安全!
评论
发表评论