0Pricing
Next.js 15 Fullstack Web Apps · Lektion

Rollenbasierte Zugriffskontrolle (RBAC)

Modellieren Sie Benutzerrollen und Berechtigungen, speichern Sie sie in der Session und setzen Sie Rollenprüfungen in Server Components, Route Handlers und Middleware einer Next.js-15-App durch.

Rollenbasierte Zugriffskontrolle (RBAC) ist eine kostenlose Next.js 15 Fullstack Web Apps-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack Web Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Häufig gestellte Fragen

Ist die Lektion „Rollenbasierte Zugriffskontrolle (RBAC)“ kostenlos?

Ja — der vollständige Text von „Rollenbasierte Zugriffskontrolle (RBAC)“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack Web Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Rollenbasierte Zugriffskontrolle (RBAC)“?

Modellieren Sie Benutzerrollen und Berechtigungen, speichern Sie sie in der Session und setzen Sie Rollenprüfungen in Server Components, Route Handlers und Middleware einer Next.js-15-App durch. Du übst Next.js 15 Fullstack Web Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Next.js 15 Fullstack Web Apps zu starten?

Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack Web Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.

Wie lange dauert die Lektion „Rollenbasierte Zugriffskontrolle (RBAC)“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Next.js 15 Fullstack Web Apps-Lektion Code schreiben und ausführen?

Ja. Jede Next.js 15 Fullstack Web Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. NextAuth.js integrieren
  2. Sitzungsverwaltung und JWTs
  3. Middleware und Zugriffskontrolle
  4. Rollenbasierte Zugriffskontrolle (RBAC)
← Zurück zu Next.js 15 Fullstack Web Apps