forbidden
此功能目前处于实验阶段,可能会有所更改,不建议用于生产环境。欢迎试用并在 GitHub 上分享您的反馈。
forbidden 函数会抛出一个错误,该错误将渲染一个 Next.js 403 错误页面。它对于处理应用程序中的授权错误非常有用。您可以使用 forbidden.js 文件自定义 UI。
要开始使用 forbidden,请在您的 next.config.js 文件中启用实验性的 authInterrupts 配置选项
next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
authInterrupts: true,
},
}
export default nextConfigforbidden 可以在服务器组件、服务器操作和路由处理程序中调用。
app/auth/page.tsx
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
export default async function AdminPage() {
const session = await verifySession()
// Check if the user has the 'admin' role
if (session.role !== 'admin') {
forbidden()
}
// Render the admin page for authorized users
return <></>
}须知
forbidden函数不能在根布局中调用。
示例
基于角色的路由保护
您可以使用 forbidden 根据用户角色限制对某些路由的访问。这确保了已通过身份验证但缺少所需权限的用户无法访问该路由。
app/admin/page.tsx
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
export default async function AdminPage() {
const session = await verifySession()
// Check if the user has the 'admin' role
if (session.role !== 'admin') {
forbidden()
}
// Render the admin page for authorized users
return (
<main>
<h1>Admin Dashboard</h1>
<p>Welcome, {session.user.name}!</p>
</main>
)
}使用服务器操作进行修改
在服务器操作中实现变更时,您可以使用 forbidden 仅允许具有特定角色的用户更新敏感数据。
app/actions/update-role.ts
'use server'
import { verifySession } from '@/app/lib/dal'
import { forbidden } from 'next/navigation'
import db from '@/app/lib/db'
export async function updateRole(formData: FormData) {
const session = await verifySession()
// Ensure only admins can update roles
if (session.role !== 'admin') {
forbidden()
}
// Perform the role update for authorized users
// ...
}版本历史
| 版本 | 更改 |
|---|---|
v15.1.0 | forbidden 已引入。 |
这有帮助吗?