如何在 Next.js 中实现身份验证
了解如何在你的 Next.js 应用中实现身份验证。
理解身份验证对于保护应用的数据至关重要。本页将指导你使用哪些 React 和 Next.js 特性来实现身份验证。
在开始之前,将整个过程拆解为三个概念会有所帮助:
下图展示了使用 React 和 Next.js 特性的身份验证流程:

本页的示例出于教学目的,演示了基本的用户名和密码身份验证。虽然你可以实现自定义的身份验证方案,但为了更高的安全性和简洁性,我们建议使用身份验证库。这些库提供了身份验证、会话管理和授权的内置解决方案,以及社交登录、多因素身份验证和基于角色的访问控制等附加功能。你可以在 身份验证库 部分找到列表。
须知:
启用 Cache Components 后,读取会话和缓存每个用户的数据需要遵循特定规则。请参阅使用 Cache Components 进行身份验证。
身份验证
注册和登录功能
你可以将 <form> 元素与 React 的服务器操作和 useActionState 结合使用,以捕获用户凭据、验证表单字段,并调用你的身份验证提供方的 API 或数据库。
由于服务器操作始终在服务器上执行,它们为处理身份验证逻辑提供了安全的环境。
以下是实现注册/登录功能的步骤:
1. 捕获用户凭据
要捕获用户凭据,请创建一个在提交时调用服务器操作的表单。例如,一个接受用户姓名、邮箱和密码的注册表单:
TypeScript
import { signup } from '@/app/actions/auth'
export function SignupForm() {
return (
<form action={signup}>
<div>
<label htmlFor="name">Name</label>
<input id="name" name="name" placeholder="Name" />
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" placeholder="Email" />
</div>
<div>
<label htmlFor="password">Password</label>
<input id="password" name="password" type="password" />
</div>
<button type="submit">Sign Up</button>
</form>
)
}
export async function signup(formData: FormData) {}
JavaScript
import { signup } from '@/app/actions/auth'
export function SignupForm() {
return (
<form action={signup}>
<div>
<label htmlFor="name">Name</label>
<input id="name" name="name" placeholder="Name" />
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" placeholder="Email" />
</div>
<div>
<label htmlFor="password">Password</label>
<input id="password" name="password" type="password" />
</div>
<button type="submit">Sign Up</button>
</form>
)
}
export async function signup(formData) {}
2. 在服务器上验证表单字段
使用服务器操作在服务器上验证表单字段。如果你的身份验证提供方不提供表单验证,你可以使用像 Zod、Valibot 或 Yup 这样的模式验证库。
以 Zod 为例,你可以定义一个带有适当错误消息的表单模式:
TypeScript
import * as z from 'zod'
export const SignupFormSchema = z.object({
name: z
.string()
.min(2, { error: 'Name must be at least 2 characters long.' })
.trim(),
email: z.email({ error: 'Please enter a valid email.' }).trim(),
password: z
.string()
.min(8, { error: 'Be at least 8 characters long' })
.regex(/[a-zA-Z]/, { error: 'Contain at least one letter.' })
.regex(/[0-9]/, { error: 'Contain at least one number.' })
.regex(/[^a-zA-Z0-9]/, {
error: 'Contain at least one special character.',
})
.trim(),
})
export type FormState =
| {
errors?: {
name?: string[]
email?: string[]
password?: string[]
}
message?: string
}
| undefined
JavaScript
import * as z from 'zod'
export const SignupFormSchema = z.object({
name: z
.string()
.min(2, { error: 'Name must be at least 2 characters long.' })
.trim(),
email: z.email({ error: 'Please enter a valid email.' }).trim(),
password: z
.string()
.min(8, { error: 'Be at least 8 characters long' })
.regex(/[a-zA-Z]/, { error: 'Contain at least one letter.' })
.regex(/[0-9]/, { error: 'Contain at least one number.' })
.regex(/[^a-zA-Z0-9]/, {
error: 'Contain at least one special character.',
})
.trim(),
})
为避免不必要地调用身份验证提供程序的 API 或数据库,如果任何表单字段与定义的 schema 不匹配,你可以在服务器操作中尽早 return。
TypeScript
import { SignupFormSchema, FormState } from '@/app/lib/definitions'
export async function signup(state: FormState, formData: FormData) {
// Validate form fields
const validatedFields = SignupFormSchema.safeParse({
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password'),
})
// If any form fields are invalid, return early
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
}
}
// Call the provider or db to create a user...
}
JavaScript
import { SignupFormSchema } from '@/app/lib/definitions'
export async function signup(state, formData) {
// Validate form fields
const validatedFields = SignupFormSchema.safeParse({
name: formData.get('name'),
email: formData.get('email'),
password: formData.get('password'),
})
// If any form fields are invalid, return early
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
}
}
// Call the provider or db to create a user...
}
回到你的 <SignupForm />,你可以使用 React 的 useActionState hook 在表单提交期间显示验证错误:
TypeScript
'use client'
import { signup } from '@/app/actions/auth'
import { useActionState } from 'react'
export default function SignupForm() {
const [state, action, pending] = useActionState(signup, undefined)
return (
<form action={action}>
<div>
<label htmlFor="name">Name</label>
<input id="name" name="name" placeholder="Name" />
</div>
{state?.errors?.name && <p>{state.errors.name}</p>}
<div>
<label htmlFor="email">Email</label>
<input id="email" name="email" placeholder="Email" />
</div>
{state?.errors?.email && <p>{state.errors.email}</p>}
<div>
<label htmlFor="password">Password</label>
<input id="password" name="password" type="password" />
</div>
{state?.errors?.password && (
<div>
<p>Password must:</p>
<ul>
{state.errors.password.map((error) => (
<li key={error}>- {error}</li>
))}
</ul>
</div>
)}
<button disabled={pending} type="submit">
Sign Up
</button>
</form>
)
}
JavaScript
'use client'
import { signup } from '@/app/actions/auth'
import { useActionState } from 'react'
export default function SignupForm() {
const [state, action, pending] = useActionState(signup, undefined)
return (
<form action={action}>
<div>
<label htmlFor="name">Name</label>
<input id="name" name="name" placeholder="Name" />
</div>
{state?.errors?.name && <p>{state.errors.name}</p>}
<div>
<label htmlFor="email">Email</label>
<input id="email" name="email" placeholder="Email" />
</div>
{state?.errors?.email && <p>{state.errors.email}</p>}
<div>
<label htmlFor="password">Password</label>
<input id="password" name="password" type="password" />
</div>
{state?.errors?.password && (
<div>
<p>Password must:</p>
<ul>
{state.errors.password.map((error) => (
<li key={error}>- {error}</li>
))}
</ul>
</div>
)}
<button disabled={pending} type="submit">
Sign Up
</button>
</form>
)
}
须知:
- 在 React 19 中,
useFormStatus返回的对象包含额外的键,例如 data、method 和 action。如果你未使用 React 19,则只有pending键可用。- 在变更数据之前,你应始终确保用户也有权执行该操作。请参阅身份验证与授权。
3. 创建用户或检查用户凭证
验证表单字段后,你可以通过调用身份验证提供程序的 API 或数据库来创建新用户账户,或检查用户是否存在。
继续上一个示例:
TypeScript
export async function signup(state: FormState, formData: FormData) {
// 1. Validate form fields
// ...
// 2. Prepare data for insertion into database
const { name, email, password } = validatedFields.data
// e.g. Hash the user's password before storing it
const hashedPassword = await bcrypt.hash(password, 10)
// 3. Insert the user into the database or call an Auth Library's API
const data = await db
.insert(users)
.values({
name,
email,
password: hashedPassword,
})
.returning({ id: users.id })
const user = data[0]
if (!user) {
return {
message: 'An error occurred while creating your account.',
}
}
// TODO:
// 4. Create user session
// 5. Redirect user
}
JavaScript
export async function signup(state, formData) {
// 1. Validate form fields
// ...
// 2. Prepare data for insertion into database
const { name, email, password } = validatedFields.data
// e.g. Hash the user's password before storing it
const hashedPassword = await bcrypt.hash(password, 10)
// 3. Insert the user into the database or call an Library API
const data = await db
.insert(users)
.values({
name,
email,
password: hashedPassword,
})
.returning({ id: users.id })
const user = data[0]
if (!user) {
return {
message: 'An error occurred while creating your account.',
}
}
// TODO:
// 4. Create user session
// 5. Redirect user
}
成功创建用户账户或验证用户凭证后,你可以创建一个会话来管理用户的身份验证状态。根据你的会话管理策略,会话可以存储在 cookie 或数据库中,也可以两者都存储。请继续阅读会话管理章节以了解更多。
提示:
- 上面的示例较为冗长,因为出于教学目的,它将身份验证步骤进行了拆解。这突显了实现自己的安全解决方案可能会很快变得复杂。可以考虑使用身份验证库来简化这一过程。
- 为了改善用户体验,你可能希望在注册流程中更早地检查重复的电子邮件或用户名。例如,在用户输入用户名时,或输入字段失去焦点时。这有助于防止不必要的表单提交,并向用户提供即时反馈。你可以使用 use-debounce 等库对请求进行防抖,以控制这些检查的频率。
会话管理
会话管理可确保用户已身份验证的状态在跨请求时得以保留。它涉及创建、存储、刷新和删除会话或令牌。
会话有两种类型:
- 无状态:会话数据(或令牌)存储在浏览器的 cookie 中。每次请求都会发送该 cookie,从而可以在服务器上验证会话。此方法更简单,但如果实现不当,安全性可能较低。
- 数据库:会话数据存储在数据库中,用户的浏览器只会收到加密的会话 ID。此方法更安全,但可能较为复杂,并会占用更多服务器资源。
须知:
虽然你可以使用其中任一方法,或同时使用两者,但我们建议使用会话管理库,例如 iron-session 或 Jose。
无状态会话
要创建和管理无状态会话,你需要遵循以下几个步骤:
除上述内容外,还可考虑添加功能:在用户返回应用时更新(或刷新)会话,并在用户登出时删除会话。
须知:
检查你的身份验证库是否包含会话管理功能。
1. 生成密钥
有几种方法可以生成用于签署会话的密钥。例如,你可以选择在终端中使用 openssl 命令:
openssl rand -base64 32
此命令会生成一个 32 字符的随机字符串,你可以将其用作密钥,并存储在环境变量文件中:
SESSION_SECRET=your_secret_key
然后,你可以在会话管理逻辑中引用此密钥:
const secretKey = process.env.SESSION_SECRET
2. 加密和解密会话
接下来,你可以使用首选的会话管理库来加密和解密会话。延续上一个示例,我们将使用 Jose 和 React 的 server-only 包,以确保你的会话管理逻辑仅在服务器上执行。
TypeScript
import 'server-only'
import { SignJWT, jwtVerify } from 'jose'
import { SessionPayload } from '@/app/lib/definitions'
const secretKey = process.env.SESSION_SECRET
const encodedKey = new TextEncoder().encode(secretKey)
export async function encrypt(payload: SessionPayload) {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('7d')
.sign(encodedKey)
}
export async function decrypt(session: string | undefined = '') {
try {
const { payload } = await jwtVerify(session, encodedKey, {
algorithms: ['HS256'],
})
return payload
} catch (error) {
console.log('Failed to verify session')
}
}
JavaScript
import 'server-only'
import { SignJWT, jwtVerify } from 'jose'
const secretKey = process.env.SESSION_SECRET
const encodedKey = new TextEncoder().encode(secretKey)
export async function encrypt(payload) {
return new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('7d')
.sign(encodedKey)
}
export async function decrypt(session) {
try {
const { payload } = await jwtVerify(session, encodedKey, {
algorithms: ['HS256'],
})
return payload
} catch (error) {
console.log('Failed to verify session')
}
}
提示:
- 载荷应包含最少的、将在后续请求中使用的唯一用户数据,例如用户 ID、角色等。它不应包含电话号码、电子邮件地址、信用卡信息等个人可识别信息,也不应包含密码等敏感数据。
3. 设置 cookie(推荐选项)
要将会话存储在 cookie 中,请使用 Next.js 的 cookies API。cookie 应在服务器上设置,并包含以下推荐选项:
- HttpOnly:阻止客户端 JavaScript 访问该 cookie。
- Secure:使用 https 发送 cookie。
- SameSite:指定 cookie 是否可以随跨站请求发送。
- Max-Age 或 Expires:在特定时间段后删除 cookie。
- Path:定义 cookie 的 URL 路径。
有关这些选项的更多信息,请参阅 MDN。
TypeScript
import 'server-only'
import { cookies } from 'next/headers'
export async function createSession(userId: string) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
const session = await encrypt({ userId, expiresAt })
const cookieStore = await cookies()
cookieStore.set('session', session, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: 'lax',
path: '/',
})
}
JavaScript
import 'server-only'
import { cookies } from 'next/headers'
export async function createSession(userId) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
const session = await encrypt({ userId, expiresAt })
const cookieStore = await cookies()
cookieStore.set('session', session, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: 'lax',
path: '/',
})
}
回到你的服务器操作中,你可以调用 createSession() 函数,并使用 redirect() API 将用户重定向到相应的页面:
TypeScript
import { createSession } from '@/app/lib/session'
export async function signup(state: FormState, formData: FormData) {
// Previous steps:
// 1. Validate form fields
// 2. Prepare data for insertion into database
// 3. Insert the user into the database or call an Library API
// Current steps:
// 4. Create user session
await createSession(user.id)
// 5. Redirect user
redirect('/profile')
}
JavaScript
import { createSession } from '@/app/lib/session'
export async function signup(state, formData) {
// Previous steps:
// 1. Validate form fields
// 2. Prepare data for insertion into database
// 3. Insert the user into the database or call an Library API
// Current steps:
// 4. Create user session
await createSession(user.id)
// 5. Redirect user
redirect('/profile')
}
提示:
- 应在服务器上设置 Cookie,以防客户端篡改。
- 🎥 观看:进一步了解无状态会话以及 Next.js 中的身份验证 → YouTube(11 分钟)。
更新(或刷新)会话
你还可以延长会话的过期时间。这在用户再次访问应用后保持其登录状态时很有用。例如:
TypeScript
import 'server-only'
import { cookies } from 'next/headers'
import { decrypt } from '@/app/lib/session'
export async function updateSession() {
const session = (await cookies()).get('session')?.value
const payload = await decrypt(session)
if (!session || !payload) {
return null
}
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
const cookieStore = await cookies()
cookieStore.set('session', session, {
httpOnly: true,
secure: true,
expires: expires,
sameSite: 'lax',
path: '/',
})
}
JavaScript
import 'server-only'
import { cookies } from 'next/headers'
import { decrypt } from '@/app/lib/session'
export async function updateSession() {
const cookieStore = await cookies()
const session = cookieStore.get('session')?.value
const payload = await decrypt(session)
if (!session || !payload) {
return null
}
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
cookieStore.set('session', session, {
httpOnly: true,
secure: true,
expires: expires,
sameSite: 'lax',
path: '/',
})
}
提示:
检查你的认证库是否支持刷新令牌,可用于延长用户的会话。
删除会话
要删除会话,你可以删除 cookie:
TypeScript
import 'server-only'
import { cookies } from 'next/headers'
export async function deleteSession() {
const cookieStore = await cookies()
cookieStore.delete('session')
}
JavaScript
import 'server-only'
import { cookies } from 'next/headers'
export async function deleteSession() {
const cookieStore = await cookies()
cookieStore.delete('session')
}
然后你可以在应用中复用 deleteSession() 函数,例如在登出时:
TypeScript
import { cookies } from 'next/headers'
import { deleteSession } from '@/app/lib/session'
export async function logout() {
await deleteSession()
redirect('/login')
}
JavaScript
import { cookies } from 'next/headers'
import { deleteSession } from '@/app/lib/session'
export async function logout() {
await deleteSession()
redirect('/login')
}
数据库会话
要创建和管理数据库会话,你需要遵循以下步骤:
- 在数据库中创建一张表来存储会话和数据(或检查你的认证库是否已处理这一点)。
- 实现插入、更新和删除会话的功能
- 在将会话 ID 存储到用户浏览器之前先对其进行加密,并确保数据库和 cookie 保持同步(这是可选的,但推荐用于在 Proxy 中进行乐观认证检查)。
例如:
TypeScript
import { cookies } from 'next/headers'
import { db } from '@/app/lib/db'
import { encrypt } from '@/app/lib/session'
export async function createSession(id: number) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
// 1. Create a session in the database
const data = await db
.insert(sessions)
.values({
userId: id,
expiresAt,
})
// Return the session ID
.returning({ id: sessions.id })
const sessionId = data[0].id
// 2. Encrypt the session ID
const session = await encrypt({ sessionId, expiresAt })
// 3. Store the session in cookies for optimistic auth checks
const cookieStore = await cookies()
cookieStore.set('session', session, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: 'lax',
path: '/',
})
}
JavaScript
import { cookies } from 'next/headers'
import { db } from '@/app/lib/db'
import { encrypt } from '@/app/lib/session'
export async function createSession(id) {
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
// 1. Create a session in the database
const data = await db
.insert(sessions)
.values({
userId: id,
expiresAt,
})
// Return the session ID
.returning({ id: sessions.id })
const sessionId = data[0].id
// 2. Encrypt the session ID
const session = await encrypt({ sessionId, expiresAt })
// 3. Store the session in cookies for optimistic auth checks
const cookieStore = await cookies()
cookieStore.set('session', session, {
httpOnly: true,
secure: true,
expires: expiresAt,
sameSite: 'lax',
path: '/',
})
}
提示:
- 为了更快的访问速度,你可以考虑在会话生命周期内添加服务器缓存。你也可以将会话数据保留在主数据库中,并合并数据请求以减少查询次数。
- 你可以选择使用数据库会话来实现更高级的用例,例如跟踪用户上次登录的时间、活跃设备的数量,或让用户能够从所有设备登出。
实现会话管理后,你需要添加授权逻辑来控制用户在应用中可以访问和执行的操作。继续阅读 Authorization 部分以了解更多。
授权
一旦用户通过身份验证并创建了会话,你就可以实现授权,来控制用户在你的应用中可以访问和执行的操作。
授权检查主要有两种类型:
- 乐观:使用存储在 cookie 中的会话数据检查用户是否有权访问某个路由或执行某个操作。这类检查适用于快速操作,例如显示/隐藏 UI 元素,或根据权限或角色重定向用户。
- 安全:使用存储在数据库中的会话数据检查用户是否有权访问某个路由或执行某个操作。这类检查更安全,适用于需要访问敏感数据或执行敏感操作的情况。
对于这两种情况,我们建议:
- 创建一个 Data Access Layer 来集中管理你的授权逻辑
- 使用 Data Transfer Objects (DTO) 只返回必要的数据
- 可选地使用 Proxy 执行乐观检查。
使用 Proxy 进行乐观检查(可选)
在某些情况下,你可能希望使用 Proxy 并根据权限重定向用户:
- 用于执行乐观检查。由于 Proxy 会在每个路由上运行,因此它是集中管理重定向逻辑并预先过滤未授权用户的好方法。
- 用于保护在用户之间共享数据的静态路由(例如付费墙后的内容)。
不过,由于 Proxy 会在每个路由上运行,包括已预取的路由,因此务必只从 cookie 中读取会话(乐观检查),并避免数据库检查以防止性能问题。
例如:
TypeScript
import { NextRequest, NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers'
// 1. Specify protected and public routes
const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/signup', '/']
export default async function proxy(req: NextRequest) {
// 2. Check if the current route is protected or public
const path = req.nextUrl.pathname
const isProtectedRoute = protectedRoutes.includes(path)
const isPublicRoute = publicRoutes.includes(path)
// 3. Decrypt the session from the cookie
const cookie = (await cookies()).get('session')?.value
const session = await decrypt(cookie)
// 4. Redirect to /login if the user is not authenticated
if (isProtectedRoute && !session?.userId) {
return NextResponse.redirect(new URL('/login', req.nextUrl))
}
// 5. Redirect to /dashboard if the user is authenticated
if (
isPublicRoute &&
session?.userId &&
!req.nextUrl.pathname.startsWith('/dashboard')
) {
return NextResponse.redirect(new URL('/dashboard', req.nextUrl))
}
return NextResponse.next()
}
// Routes Proxy should not run on
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
JavaScript
import { NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers'
// 1. Specify protected and public routes
const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/signup', '/']
export default async function proxy(req) {
// 2. Check if the current route is protected or public
const path = req.nextUrl.pathname
const isProtectedRoute = protectedRoutes.includes(path)
const isPublicRoute = publicRoutes.includes(path)
// 3. Decrypt the session from the cookie
const cookie = (await cookies()).get('session')?.value
const session = await decrypt(cookie)
// 5. Redirect to /login if the user is not authenticated
if (isProtectedRoute && !session?.userId) {
return NextResponse.redirect(new URL('/login', req.nextUrl))
}
// 6. Redirect to /dashboard if the user is authenticated
if (
isPublicRoute &&
session?.userId &&
!req.nextUrl.pathname.startsWith('/dashboard')
) {
return NextResponse.redirect(new URL('/dashboard', req.nextUrl))
}
return NextResponse.next()
}
// Routes Proxy should not run on
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
虽然 Proxy 对于初始检查可能有用,但它不应成为保护数据的唯一防线。大多数安全检查应尽可能靠近数据源执行,更多信息请参阅数据访问层。
提示:
- 在 Proxy 中,你也可以使用
req.cookies.get('session')?.value读取 cookie。- Proxy 使用 Node.js 运行时,请检查你的认证库和会话管理库是否兼容。
- 你可以使用 Proxy 中的
matcher属性来指定 Proxy 应在哪些路由上运行。不过,对于认证,建议让 Proxy 在所有路由上运行。
创建数据访问层(DAL)
我们建议创建一个 DAL,以集中管理数据请求和授权逻辑。
DAL 应包含一个函数,在用户与应用交互时验证其会话。至少,该函数应检查会话是否有效,然后重定向或返回进行后续请求所需的用户信息。
例如,为你的 DAL 创建一个单独的文件,其中包含 verifySession() 函数。然后使用 React 的 cache API 在 React 渲染过程中对该函数的返回值进行记忆化:
TypeScript
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { decrypt } from '@/app/lib/session'
export const verifySession = cache(async () => {
const cookie = (await cookies()).get('session')?.value
const session = await decrypt(cookie)
if (!session?.userId) {
redirect('/login')
}
return { isAuth: true, userId: session.userId }
})
JavaScript
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { decrypt } from '@/app/lib/session'
export const verifySession = cache(async () => {
const cookie = (await cookies()).get('session')?.value
const session = await decrypt(cookie)
if (!session.userId) {
redirect('/login')
}
return { isAuth: true, userId: session.userId }
})
然后,你可以在数据请求、服务器操作和路由处理器中调用 verifySession() 函数:
须知:
React 的
cache会在单次 React 渲染过程中去重。服务器操作和路由处理器不属于渲染过程,因此该包装不会起任何作用,每次调用都会执行该函数。
TypeScript
export const getUser = cache(async () => {
const session = await verifySession()
if (!session) return null
try {
const data = await db.query.users.findMany({
where: eq(users.id, session.userId),
// Explicitly return the columns you need rather than the whole user object
columns: {
id: true,
name: true,
email: true,
},
})
const user = data[0]
return user
} catch (error) {
console.log('Failed to fetch user')
return null
}
})
JavaScript
export const getUser = cache(async () => {
const session = await verifySession()
if (!session) return null
try {
const data = await db.query.users.findMany({
where: eq(users.id, session.userId),
// Explicitly return the columns you need rather than the whole user object
columns: {
id: true,
name: true,
email: true,
},
})
const user = data[0]
return user
} catch (error) {
console.log('Failed to fetch user')
return null
}
})
提示:
使用数据传输对象(DTO)
检索数据时,建议只返回应用程序中将要用到的必要数据,而不是整个对象。例如,如果你在获取用户数据,可能只需返回用户的 ID 和姓名,而不是可能包含密码、电话号码等信息的整个用户对象。
但是,如果你无法控制返回的数据结构,或者在团队协作中希望避免将整个对象传递给客户端,你可以采用一些策略,例如指定哪些字段可以安全地暴露给客户端。
TypeScript
import 'server-only'
import { getUser } from '@/app/lib/dal'
function canSeeUsername(viewer: User) {
return true
}
function canSeePhoneNumber(viewer: User, team: string) {
return viewer.isAdmin || team === viewer.team
}
export async function getProfileDTO(slug: string) {
const data = await db.query.users.findMany({
where: eq(users.slug, slug),
// Return specific columns here
})
const user = data[0]
const currentUser = await getUser(user.id)
// Or return only what's specific to the query here
return {
username: canSeeUsername(currentUser) ? user.username : null,
phonenumber: canSeePhoneNumber(currentUser, user.team)
? user.phonenumber
: null,
}
}
JavaScript
import 'server-only'
import { getUser } from '@/app/lib/dal'
function canSeeUsername(viewer) {
return true
}
function canSeePhoneNumber(viewer, team) {
return viewer.isAdmin || team === viewer.team
}
export async function getProfileDTO(slug) {
const data = await db.query.users.findMany({
where: eq(users.slug, slug),
// Return specific columns here
})
const user = data[0]
const currentUser = await getUser(user.id)
// Or return only what's specific to the query here
return {
username: canSeeUsername(currentUser) ? user.username : null,
phonenumber: canSeePhoneNumber(currentUser, user.team)
? user.phonenumber
: null,
}
}
通过将数据请求和授权逻辑集中到 DAL 中并使用 DTO,你可以确保所有数据请求都安全且一致,使应用程序在扩展时更易于维护、审计和调试。
须知:
- 定义 DTO 有多种方式,从使用
toJSON(),到像上面示例那样的单个函数,再到 JS 类。由于这些是 JavaScript 模式,而不是 React 或 Next.js 的功能,我们建议你做一些研究,为你的应用程序找到最合适的模式。- 在我们的 Security in Next.js 文章中了解更多安全最佳实践。
服务器组件
在服务器组件中进行身份验证检查对于基于角色的访问控制很有用。例如,要根据用户的角色有条件地渲染组件:
TypeScript
import { verifySession } from '@/app/lib/dal'
export default async function Dashboard() {
const session = await verifySession()
const userRole = session?.role // Assuming 'role' is part of the session object
if (userRole === 'admin') {
return <AdminDashboard />
} else if (userRole === 'user') {
return <UserDashboard />
} else {
redirect('/login')
}
}
JavaScript
import { verifySession } from '@/app/lib/dal'
export default async function Dashboard() {
const session = await verifySession()
const userRole = session?.role // Assuming 'role' is part of the session object
if (userRole === 'admin') {
return <AdminDashboard />
} else if (userRole === 'user') {
return <UserDashboard />
} else {
redirect('/login')
}
}
在示例中,我们使用 DAL 中的 verifySession() 函数来检查 'admin'、'user' 和未授权角色。这种模式确保每个用户只与其角色相应的组件进行交互。
布局与身份验证检查
由于部分渲染,在布局中执行检查时要谨慎,因为布局在导航时不会重新渲染,这意味着不会在每次路由变化时检查用户会话。
布局也无法控制路由的其余部分是否渲染。路由段和并行路由插槽由路由器渲染,因此,隐藏或替换它们的布局并不能阻止它们运行,也不能阻止它们出现在 RSC Payload 中。
相反,你应该在靠近数据源或将要进行条件渲染的组件的位置执行检查。
例如,假设有一个共享布局,它获取用户数据并在导航栏中显示用户头像。你应该在布局中获取用户数据(getUser()),并在 DAL 中执行身份验证检查,而不是在布局中执行检查。
这保证了在应用程序中任何调用 getUser() 的地方都会执行身份验证检查,并防止开发者忘记检查用户是否有权访问数据。
身份验证与流式渲染
会话和用户数据经常出现在跨路由重复的外壳 UI(页头、导航)中。在布局中对 cookies()、headers() 或 DAL 进行顶层 await,会延迟该段第一个流式数据块的输出,并使 {children} 被这项工作阻塞。
如果外壳中只有一部分需要会话数据(例如用户菜单),请将 await 移入嵌套的服务器组件,并用 <Suspense> 包裹它,以便页面其余部分先进行流式渲染。该模式参见将动态访问下推。
客户端组件无法导入 DAL。请在父级服务器组件中运行 verifySession()、getUser() 或类似方法,然后通过 props 或上下文提供程序将数据传递给客户端子组件。该模式参见在 Context Provider 中使用 React 的 use,并使用 React 的 taintUniqueValue API 防止敏感会话字段到达客户端。
页面组件中的身份验证检查
例如,在仪表盘页面中,你可以验证用户会话并获取用户数据:
TypeScript
import { verifySession } from '@/app/lib/dal'
export default async function DashboardPage() {
const session = await verifySession()
// Fetch user-specific data from your database or data source
const user = await getUserData(session.userId)
return (
<div>
<h1>Welcome, {user.name}</h1>
{/* Dashboard content */}
</div>
)
}
JavaScript
import { verifySession } from '@/app/lib/dal'
export default async function DashboardPage() {
const session = await verifySession()
// Fetch user-specific data from your database or data source
const user = await getUserData(session.userId)
return (
<div>
<h1>Welcome, {user.name}</h1>
{/* Dashboard content */}
</div>
)
}
叶子组件中的身份验证检查
你也可以在叶子组件中执行身份验证检查,根据用户权限有条件地渲染 UI 元素。例如,一个显示仅限管理员操作的组件:
TypeScript
import { verifySession } from '@/app/lib/dal'
export default async function AdminActions() {
const session = await verifySession()
const userRole = session?.role
if (userRole !== 'admin') {
return null
}
return (
<div>
<button>Delete User</button>
<button>Edit Settings</button>
</div>
)
}
JavaScript
import { verifySession } from '@/app/lib/dal'
export default async function AdminActions() {
const session = await verifySession()
const userRole = session?.role
if (userRole !== 'admin') {
return null
}
return (
<div>
<button>Delete User</button>
<button>Edit Settings</button>
</div>
)
}
此模式允许你根据用户权限显示或隐藏 UI 元素,同时确保身份验证检查在每个组件的渲染时进行。
须知:
- 在 SPA 中,一种常见模式是:如果用户未获授权,就在布局或顶层组件中
return null。此模式不建议使用,因为 Next.js 应用有多个入口点,这无法阻止嵌套路由段和服务器操作被访问。- 确保从这些组件调用的任何服务器操作也执行自己的授权检查,因为仅靠客户端 UI 限制不足以保障安全。
服务器操作
像对待面向公众的 API 端点一样,对服务器操作采用相同的安全考量,并验证用户是否被允许执行变更。
在下面的示例中,我们在允许操作继续之前检查用户的角色:
TypeScript
'use server'
import { verifySession } from '@/app/lib/dal'
export async function serverAction(formData: FormData) {
const session = await verifySession()
const userRole = session?.role
// Return early if user is not authorized to perform the action
if (userRole !== 'admin') {
return null
}
// Proceed with the action for authorized users
}
JavaScript
'use server'
import { verifySession } from '@/app/lib/dal'
export async function serverAction() {
const session = await verifySession()
const userRole = session?.role
// Return early if user is not authorized to perform the action
if (userRole !== 'admin') {
return null
}
// Proceed with the action for authorized users
}
路由处理器
像对待面向公众的 API 端点一样,对路由处理器采用相同的安全考量,并验证用户是否被允许访问该路由处理器。
例如:
TypeScript
import { verifySession } from '@/app/lib/dal'
export async function GET() {
// User authentication and role verification
const session = await verifySession()
// Check if the user is authenticated
if (!session) {
// User is not authenticated
return new Response(null, { status: 401 })
}
// Check if the user has the 'admin' role
if (session?.role !== 'admin') {
// User is authenticated but does not have the right permissions
return new Response(null, { status: 403 })
}
// Continue for authorized users
}
JavaScript
import { verifySession } from '@/app/lib/dal'
export async function GET() {
// User authentication and role verification
const session = await verifySession()
// Check if the user is authenticated
if (!session) {
// User is not authenticated
return new Response(null, { status: 401 })
}
// Check if the user has the 'admin' role
if (session?.role !== 'admin') {
// User is authenticated but does not have the right permissions
return new Response(null, { status: 403 })
}
// Continue for authorized users
}
上面的示例演示了一个带有两级安全检查的路由处理器。它首先检查是否存在活动会话,然后验证已登录用户是否为 'admin'。
资源
既然你已经了解了 Next.js 中的身份验证,以下是与 Next.js 兼容的库和资源,可帮助你实现安全的身份验证和会话管理:
身份验证库
会话管理库
延伸阅读
如需继续学习身份验证和安全相关知识,请查看以下资源: