跳到内容
API 参考函数unauthorized

unauthorized

此功能目前为实验性功能,可能会发生变化,不建议在生产环境中使用。请试用并分享您在 GitHub 上的反馈。

unauthorized 函数会抛出一个错误,该错误会渲染 Next.js 401 错误页面。它对于处理应用程序中的授权错误很有用。您可以使用 unauthorized.js 文件来自定义 UI。

要开始使用 unauthorized,请在您的 next.config.js 文件中启用实验性 authInterrupts 配置选项

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  experimental: {
    authInterrupts: true,
  },
}
 
export default nextConfig

可以在服务器组件服务器行为路由处理器中调用 unauthorized

app/dashboard/page.tsx
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export default async function DashboardPage() {
  const session = await verifySession()
 
  if (!session) {
    unauthorized()
  }
 
  // Render the dashboard for authenticated users
  return (
    <main>
      <h1>Welcome to the Dashboard</h1>
      <p>Hi, {session.user.name}.</p>
    </main>
  )
}

须知

  • unauthorized 函数不能在根布局中调用。

示例

向未认证用户显示登录 UI

您可以使用 unauthorized 函数来显示带有登录 UI 的 unauthorized.js 文件。

app/dashboard/page.tsx
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export default async function DashboardPage() {
  const session = await verifySession()
 
  if (!session) {
    unauthorized()
  }
 
  return <div>Dashboard</div>
}
app/unauthorized.tsx
import Login from '@/app/components/Login'
 
export default function UnauthorizedPage() {
  return (
    <main>
      <h1>401 - Unauthorized</h1>
      <p>Please log in to access this page.</p>
      <Login />
    </main>
  )
}

使用服务器行为进行变更

您可以在服务器行为中调用 unauthorized,以确保只有经过身份验证的用户才能执行特定的变更。

app/actions/update-profile.ts
'use server'
 
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
import db from '@/app/lib/db'
 
export async function updateProfile(data: FormData) {
  const session = await verifySession()
 
  // If the user is not authenticated, return a 401
  if (!session) {
    unauthorized()
  }
 
  // Proceed with mutation
  // ...
}

使用路由处理器获取数据

您可以在路由处理器中使用 unauthorized,以确保只有经过身份验证的用户才能访问该端点。

app/api/profile/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { verifySession } from '@/app/lib/dal'
import { unauthorized } from 'next/navigation'
 
export async function GET(req: NextRequest): Promise<NextResponse> {
  // Verify the user's session
  const session = await verifySession()
 
  // If no session exists, return a 401 and render unauthorized.tsx
  if (!session) {
    unauthorized()
  }
 
  // Fetch data
  // ...
}

版本历史

版本变更
v15.1.0引入了 unauthorized