如何思考 Next.js 中的数据安全
了解 Next.js 内置的数据安全功能,并学习保护应用程序数据的最佳实践。
React 服务器组件提升了性能并简化了数据获取,但也改变了数据访问的位置和方式,从而改变了前端应用中处理数据的一些传统安全假设。
本指南将帮助你理解如何思考 Next.js 中的数据安全,以及如何实施最佳实践。
数据获取方式
根据项目的规模和年限,我们推荐在 Next.js 中采用三种主要的数据获取方式:
我们建议选择一种数据获取方式,并避免混用。这样可以让在你的代码库中工作的开发者和安全审计人员都清楚地知道预期是什么。
外部 HTTP API
在现有项目中采用服务器组件时,你应该遵循 零信任 模型。你可以继续使用 fetch 从服务器组件调用现有的 API 端点(例如 REST 或 GraphQL),就像在客户端组件中一样。
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const token = cookieStore.get('AUTH_TOKEN')?.value
const res = await fetch('https://api.example.com/profile', {
headers: {
Cookie: `AUTH_TOKEN=${token}`,
// Other headers
},
})
// ....
}
这种方式适用于以下情况:
- 你已经有现成的安全实践。
- 独立的后端团队使用其他语言或独立管理 API。
数据访问层
对于新项目,我们建议创建一个专用的 数据访问层(DAL)。这是一个内部库,用于控制数据获取的方式和时机,以及哪些数据会被传递到你的渲染上下文。
数据访问层应该:
- 仅在服务器上运行。
- 执行授权检查。
- 返回安全、精简的 数据传输对象(DTO)。
这种方式集中了所有数据访问逻辑,使一致的访问控制更容易实施,并降低了授权缺陷的风险。你还能够受益于在请求的不同部分之间共享内存缓存。
import { cache } from 'react'
import { cookies } from 'next/headers'
// Cached helper methods makes it easy to get the same value in many places
// without manually passing it around. This discourages passing it from Server
// Component to Server Component which minimizes risk of passing it to a Client
// Component.
export const getCurrentUser = cache(async () => {
const cookieStore = await cookies()
const token = cookieStore.get('AUTH_TOKEN')
const decodedToken = await decryptAndValidate(token)
// Don't include secret tokens or private information as public fields.
// Use classes to avoid accidentally passing the whole object to the client.
return new User(decodedToken.id)
})
import 'server-only'
import { getCurrentUser } from './auth'
function canSeeUsername(viewer: User) {
// Public info for now, but can change
return true
}
function canSeePhoneNumber(viewer: User, team: string) {
// Privacy rules
return viewer.isAdmin || team === viewer.team
}
export async function getProfileDTO(slug: string) {
// Don't pass values, read back cached values, also solves context and easier to make it lazy
// use a database API that supports safe templating of queries
const [rows] = await sql`SELECT * FROM user WHERE slug = ${slug}`
const userData = rows[0]
const currentUser = await getCurrentUser()
// only return the data relevant for this query and not everything
// <https://www.w3.org/2001/tag/doc/APIMinimization>
return {
username: canSeeUsername(currentUser) ? userData.username : null,
phonenumber: canSeePhoneNumber(currentUser, userData.team)
? userData.phonenumber
: null,
}
}
import { getProfileDTO } from '../../data/user-dto'
export default async function Page({ params }) {
const { slug } = await params
// This page can now safely pass around this profile knowing
// that it shouldn't contain anything sensitive.
const profile = await getProfileDTO(slug)
...
}
须知:
密钥应存储在环境变量中,但只有数据访问层才应访问
process.env。这可以防止密钥暴露给应用程序的其他部分。
组件级数据访问
对于快速原型和迭代,数据库查询可以直接放在服务器组件中。
然而,这种做法更容易意外地将私有数据暴露给客户端,例如:
import Profile from './components/profile.tsx'
export default async function Page({ params }) {
const { slug } = await params
const [rows] = await sql`SELECT * FROM user WHERE slug = ${slug}`
const userData = rows[0]
// EXPOSED: This exposes all the fields in userData to the client because
// we are passing the data from the Server Component to the Client.
return <Profile user={userData} />
}
'use client'
// BAD: This is a bad props interface because it accepts way more data than the
// Client Component needs and it encourages server components to pass all that
// data down. A better solution would be to accept a limited object with just
// the fields necessary for rendering the profile.
export default async function Profile({ user }: { user: User }) {
return (
<div>
<h1>{user.name}</h1>
...
</div>
)
}
在将数据传递给客户端组件之前,你应该先对数据进行净化处理:
import { sql } from './db'
export async function getUser(slug: string) {
const [rows] = await sql`SELECT * FROM user WHERE slug = ${slug}`
const user = rows[0]
// Return only the public fields
return {
name: user.name,
}
}
import { getUser } from '../data/user'
import Profile from './ui/profile'
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const publicProfile = await getUser(slug)
return <Profile user={publicProfile} />
}
读取数据
从服务器向客户端传递数据
在初始加载时,服务器组件和客户端组件都会在服务器上运行以生成 HTML。不过,它们运行在相互隔离的模块系统中。这确保了服务器组件可以访问私有数据和 API,而客户端组件则不能。
服务器组件:
- 仅在服务器上运行。
- 可以安全地访问环境变量、密钥、数据库和内部 API。
客户端组件:
- 在预渲染期间会在服务器上运行,但必须遵循与在浏览器中运行的代码相同的安全假设。
- 不得访问特权数据或仅限服务器的模块。
这确保了应用默认是安全的,但数据获取或传递给组件的方式仍可能意外泄露私有数据。
污染标记
为防止私有数据被意外暴露给客户端,你可以使用 React 污染标记 API:
experimental_taintObjectReference,用于数据对象。experimental_taintUniqueValue,用于特定值。
你可以在 next.config.js 中使用 experimental.taint 选项,在 Next.js 应用中启用该功能:
module.exports = {
experimental: {
taint: true,
},
}
这可以防止被标记污染的对象或值传递给客户端。不过,这只是一层额外的保护,你仍应在将数据传递到 React 的渲染上下文之前,在 DAL 中过滤并净化数据。
须知:
- 默认情况下,环境变量仅在服务器上可用。Next.js 会将任何以
NEXT_PUBLIC_为前缀的环境变量暴露给客户端。了解更多。- 默认情况下,函数和类已经无法传递给客户端组件。
防止仅限服务器的代码在客户端执行
为了防止仅限服务器端运行的代码在客户端被执行,你可以使用 server-only 包来标记模块:
import 'server-only'
//...
如果该模块在客户端环境中被导入,就会触发构建错误,从而确保专有代码或内部业务逻辑保留在服务器端。
Next.js 会在内部处理 server-only 导入,并不会使用 NPM 中这些包的内容。不过,如果你的 lint 规则会将多余的依赖标记为问题,你可以安装它们以避免出现问题。
npm
npm install server-only
yarn
yarn add server-only
pnpm
pnpm add server-only
bun
bun add server-only
在防止环境中毒章节中了解更多关于 server-only 的内容。
修改数据
Next.js 使用服务器操作处理数据变更。
服务器操作的内置安全特性
默认情况下,服务器操作一经创建并导出,就可以通过直接的 POST 请求访问,而不仅限于通过应用程序的 UI 访问。这意味着,即使某个服务器操作或工具函数没有在代码的其他位置被导入,它仍然可以被外部调用。
为了提升安全性,Next.js 提供了以下内置特性:
- 安全的操作 ID:Next.js 会创建加密的、非确定性的 ID,使客户端能够引用并调用服务器操作。这些 ID 会在各次构建之间定期重新计算,以增强安全性。
- 死代码消除:未使用的服务器操作(通过其 ID 引用)会从客户端 bundle 中移除,以避免被公开访问。
须知:
这些 ID 在编译期间创建,最长缓存 14 天。当发起新的构建或构建缓存失效时,它们将被重新生成。 这项安全改进降低了缺少身份验证层时的风险。不过,你仍应将服务器操作视为可通过直接 POST 请求访问的入口,并在每个操作内部验证身份验证和授权。
// app/actions.js
'use server'
// If this action **is** used in our application, Next.js
// will create a secure ID to allow the client to reference
// and call the Server Action.
export async function updateUserAction(formData) {}
// If this action **is not** used in our application, Next.js
// will automatically remove this code during `next build`
// and will not create a public endpoint.
export async function deleteUserAction(formData) {}
验证客户端输入
你应始终验证来自客户端的输入,因为它们很容易被修改。例如表单数据、URL 参数、请求头和 searchParams:
// BAD: Trusting searchParams directly
export default async function Page({ searchParams }) {
const isAdmin = (await searchParams).isAdmin
if (isAdmin === 'true') {
// Vulnerable: relies on untrusted client data
return <AdminPanel />
}
}
// GOOD: Re-verify every time
import { cookies } from 'next/headers'
import { verifyAdmin } from './auth'
export default async function Page() {
const cookieStore = await cookies()
const token = cookieStore.get('AUTH_TOKEN')
const isAdmin = await verifyAdmin(token)
if (isAdmin) {
return <AdminPanel />
}
}
身份验证与授权
页面级的身份验证检查不会延伸到其中定义的服务器操作。请始终在操作内部重新验证:
import { auth } from '@/lib/auth'
import { redirect } from 'next/navigation'
export default async function AdminPage() {
const session = await auth()
if (!session?.user?.isAdmin) {
redirect('/login')
}
return (
<form
action={async () => {
'use server'
const session = await auth()
if (!session?.user?.isAdmin) {
throw new Error('Unauthorized')
}
await db.record.deleteMany()
}}
>
<button>Delete Records</button>
</form>
)
}
操作内部高亮的 auth() 检查至关重要。第 6 行的页面级重定向控制渲染哪个 UI,但服务器操作是一个独立的入口点,必须自行验证调用方。
除了身份验证(用户是否已登录?)之外,还要记得检查授权(该用户是否有权限操作此特定资源?)。这可以防止不安全的直接对象引用(IDOR)漏洞:
'use server'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const post = await db.post.findUnique({ where: { id: postId } })
// Check that the user owns this resource
if (post.authorId !== session.user.id) {
throw new Error('Forbidden')
}
await db.post.delete({ where: { id: postId } })
}
在 Next.js 中了解关于身份验证的更多信息。
使用数据访问层处理变更操作
正如我们建议使用数据访问层来读取数据一样,你也可以将同样的模式应用到变更操作中。这样可以将身份验证、授权和数据库逻辑放在专用的 server-only 模块中,同时让 "use server" 操作保持精简。
import 'server-only'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
export async function deletePost(postId: string) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
const post = await db.post.findUnique({ where: { id: postId } })
if (post.authorId !== session.user.id) {
throw new Error('Forbidden')
}
await db.post.delete({ where: { id: postId } })
}
然后,"use server" 操作会委托给 DAL:
'use server'
import { deletePost } from '@/data/posts'
import { revalidatePath } from 'next/cache'
export async function deletePostAction(postId: string) {
await deletePost(postId) // Auth + authz happen inside the DAL
revalidatePath('/posts')
}
须知:
你可以在数据访问层和
"use server"文件本身中使用import 'server-only'。当把该操作导入到客户端组件时(例如,将其传递给useActionState),这两种方式都能正常工作,因为"use server"模块是在仅限服务器的 webpack 层中解析的。
控制返回值
服务器操作的返回值会被序列化并发送到客户端。只返回 UI 所需的内容,而不要返回原始数据库记录。
'use server'
import { auth } from '@/lib/auth'
import { db } from '@/lib/db'
// BAD: Returns the full database record, which may include
// internal fields the client should not see.
export async function updateUser(data: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
return db.user.update({
where: { id: session.user.id },
data: { name: data.get('name') as string },
})
}
// GOOD: Returns only what the client needs.
export async function updateUserSafe(data: FormData) {
const session = await auth()
if (!session?.user) {
throw new Error('Unauthorized')
}
await db.user.update({
where: { id: session.user.id },
data: { name: data.get('name') as string },
})
return { success: true }
}
速率限制
对于开销较大的操作(发送电子邮件、写入数据库),可以考虑添加速率限制以防止滥用。请参阅 Backend for Frontend 指南中的速率限制示例。
闭包与加密
在组件内部定义服务器操作会创建一个闭包,使该操作可以访问外部函数的作用域。例如,publish 操作可以访问 publishVersion 变量:
TypeScript
export default async function Page() {
const publishVersion = await getLatestVersion();
async function publish() {
"use server";
if (publishVersion !== await getLatestVersion()) {
throw new Error('The version has changed since pressing publish');
}
...
}
return (
<form>
<button formAction={publish}>Publish</button>
</form>
);
}
JavaScript
export default async function Page() {
const publishVersion = await getLatestVersion();
async function publish() {
"use server";
if (publishVersion !== await getLatestVersion()) {
throw new Error('The version has changed since pressing publish');
}
...
}
return (
<form>
<button formAction={publish}>Publish</button>
</form>
);
}
当你需要在渲染时捕获数据的快照(例如 publishVersion),以便稍后在调用该操作时使用,闭包就很有用。
然而,为此,被捕获的变量会在调用该操作时发送到客户端,再传回服务器。为了防止敏感数据暴露给客户端,Next.js 会自动加密这些被闭包捕获的变量。每次构建 Next.js 应用时,都会为每个操作生成一个新的私钥。这意味着操作只能针对特定构建进行调用。
须知:
我们不建议仅依靠加密来防止敏感值在客户端暴露。
覆盖加密密钥(高级)
当在多个服务器上自托管 Next.js 应用时,每个服务器实例最终可能会使用不同的加密密钥,从而导致潜在的不一致。
为缓解此问题,你可以使用 process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY 环境变量覆盖加密密钥。指定该变量可确保加密密钥在多次构建之间保持持久,并且所有服务器实例都使用相同的密钥。
该密钥必须是 base64 编码的值,其解码后的长度需符合有效的 AES 密钥大小(16、24 或 32 字节)。Next.js 默认生成 32 字节的密钥。你可以使用所在平台的加密工具生成兼容的密钥,例如:
openssl rand -base64 32
这是一个高级用例,适用于在多个部署之间保持一致加密行为对应用至关重要的场景。请遵循密钥轮换和签名等标准安全实践。有关特定部署的注意事项,请参阅自托管指南。
允许的来源(高级)
由于服务器操作可以在 <form> 元素中被调用,这就使它们面临 CSRF 攻击 的风险。
在幕后,服务器操作使用 POST 方法,并且只允许使用这一 HTTP 方法来调用它们。这可以防止现代浏览器中的大多数 CSRF 漏洞,尤其是在默认启用 SameSite cookies 的情况下。
作为额外的保护措施,Next.js 中的服务器操作还会将 Origin 标头 与 Host 标头(或 X-Forwarded-Host)进行比较。如果它们不匹配,请求将被中止。换言之,服务器操作只能在承载它的页面所在的主机上调用。
对于使用反向代理或多层后端架构(其中服务器 API 与生产域名不同)的大型应用,建议使用 experimental.serverActions.allowedOrigins 选项来指定额外的受信任主机。该选项接受一个字符串数组。
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
serverActions: {
allowedOrigins: ['my-proxy.com', '*.my-proxy.com'],
},
},
}
进一步了解 安全性和服务器操作。
避免渲染期间的副作用
变更操作(例如让用户登出、更新数据库、使缓存失效)绝不应成为副作用,无论是在服务器组件还是客户端组件中。Next.js 明确禁止在渲染方法内设置 cookie 或触发缓存重新验证,以避免意外的副作用。
// BAD: Triggering a mutation during rendering
export default async function Page({ searchParams }) {
if ((await searchParams).logout) {
const cookieStore = await cookies()
cookieStore.delete('AUTH_TOKEN')
}
return <UserProfile />
}
相反,你应使用服务器操作来处理数据变更。
// GOOD: Using Server Actions to handle mutations
import { logout } from './actions'
export default function Page() {
return (
<>
<UserProfile />
<form action={logout}>
<button type="submit">Logout</button>
</form>
</>
)
}
须知:
Next.js 使用
POST请求来处理变更。这可以防止 GET 请求造成意外副作用,从而降低跨站请求伪造(CSRF)风险。
审计
如果你正在审计一个 Next.js 项目,以下是我们建议额外关注的一些事项:
- 数据访问层: 是否存在隔离数据访问层的既定实践?请确认数据库包和环境变量没有在数据访问层之外被导入。
"use client"文件: 组件的 props 是否期望私有数据?类型签名是否过于宽泛?"use server"文件: 操作参数是否在操作中或数据访问层内部进行了验证?是否在操作内部重新对用户进行授权?操作是否检查资源的所有权(即授权,而不仅仅是身份验证)?返回值是否经过筛选,仅保留客户端所需的内容?数据库访问是否委托给server-only数据访问层?/[param]/.带方括号的文件夹代表用户输入。params 是否经过验证?proxy.ts和route.ts: 拥有很大的能力。请额外花时间使用传统技术对它们进行审计。定期执行渗透测试或漏洞扫描,或与团队的软件开发生命周期保持同步。
后续步骤
进一步了解本指南中提到的主题。