0Pricing
Next.js 15 Fullstack Web Apps · 课时

基于角色的访问控制(RBAC)

建模用户角色和权限,将其存储在会话中,并在 Next.js 15 应用的服务器组件、路由处理器和中间件中执行角色检查。

基于角色的访问控制(RBAC) 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Authorization Beyond Login

Authentication answers who are you; authorization answers what may you do. Role-Based Access Control (RBAC) assigns each user one or more roles and grants permissions to roles instead of individuals.

  • Roles: admin, editor, viewer
  • Permissions are derived from the role.

Storing the Role in the JWT

With NextAuth, attach the role to the token in the jwt callback so it travels with every request without a database hit.

callbacks: {
  async jwt({ token, user }) {
    if (user) token.role = user.role;
    return token;
  },
  async session({ session, token }) {
    session.user.role = token.role;
    return session;
  },
}

A Permissions Map

Centralize what each role can do. A simple map keeps checks consistent and easy to audit.

export const permissions = {
  admin: ['read', 'write', 'delete'],
  editor: ['read', 'write'],
  viewer: ['read'],
};

export function can(role, action) {
  return permissions[role]?.includes(action) ?? false;
}

Testing the Helper

The can helper is pure logic, so it runs anywhere. Here is a self-contained check.

const permissions = {
  admin: ['read', 'write', 'delete'],
  editor: ['read', 'write'],
  viewer: ['read'],
};
function can(role, action) {
  return permissions[role]?.includes(action) ?? false;
}
console.log(can('editor', 'write'));
console.log(can('viewer', 'delete'));

Guarding a Server Component

Read the session on the server and redirect users who lack the required role before any sensitive UI renders.

import { auth } from '@/auth';
import { redirect } from 'next/navigation';

export default async function AdminPage() {
  const session = await auth();
  if (session?.user.role !== 'admin') redirect('/');
  return <h1>Admin Dashboard</h1>;
}

Guarding a Route Handler

API route handlers must enforce roles too. Never trust the client. Return 403 when the role is insufficient.

import { auth } from '@/auth';
import { can } from '@/lib/rbac';

export async function DELETE(req) {
  const session = await auth();
  if (!can(session?.user.role, 'delete')) {
    return new Response('Forbidden', { status: 403 });
  }
  return Response.json({ ok: true });
}

Role Checks in Middleware

Middleware can block whole route groups early. Match an admin prefix and verify the token's role.

import { NextResponse } from 'next/server';

export function middleware(req) {
  const role = req.cookies.get('role')?.value;
  if (req.nextUrl.pathname.startsWith('/admin') && role !== 'admin') {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/admin/:path*'] };

Defense in Depth

Apply checks at multiple layers. Middleware gives a fast first gate, but always re-verify in the server component or route handler that actually touches data.

  • Middleware: coarse routing gate.
  • Server component / handler: authoritative check.

Hiding UI Conditionally

Hide controls users cannot use, but remember UI hiding is convenience, not security. The server must still reject unauthorized actions.

export default async function Toolbar() {
  const session = await auth();
  return (
    <div>
      {can(session?.user.role, 'delete') && <DeleteButton />}
    </div>
  );
}

Multiple Roles and Scopes

Real apps often give a user several roles or fine-grained scopes. Store an array and check membership. This scales toward permission-based (ABAC) systems later.

function hasRole(userRoles, required) {
  return userRoles.some((r) => r === required);
}
console.log(hasRole(['editor', 'viewer'], 'editor'));

Common Pitfalls

Avoid these RBAC mistakes:

  • Trusting a role sent from the client body.
  • Checking roles only in the UI.
  • Forgetting to re-issue the JWT after a role change.
  • Hardcoding role strings instead of a central map.

Quick Check

Where is the authoritative place to enforce that only admins can delete a record?

Recap

You implemented RBAC end to end:

  • Stored the role in the JWT and session via NextAuth callbacks.
  • Centralized permissions with a can() helper.
  • Guarded server components, route handlers, and middleware.
  • Applied defense in depth and avoided client-trust pitfalls.

常见问题解答

「基于角色的访问控制(RBAC)」课时是免费的吗?

是的 — 「基于角色的访问控制(RBAC)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「基于角色的访问控制(RBAC)」这节课中我会学到什么?

建模用户角色和权限,将其存储在会话中,并在 Next.js 15 应用的服务器组件、路由处理器和中间件中执行角色检查。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack Web Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「基于角色的访问控制(RBAC)」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 集成 NextAuth.js
  2. 会话管理与 JWT
  3. 中间件与访问控制
  4. 基于角色的访问控制(RBAC)
← 返回 Next.js 15 Fullstack Web Apps