Controllo degli accessi basato sui ruoli (RBAC)
Modelli ruoli e autorizzazioni degli utenti, li memorizzi nella sessione e applichi i controlli dei ruoli tra Server Components, route handler e middleware in un’app Next.js 15.
Controllo degli accessi basato sui ruoli (RBAC) è una lezione Next.js 15 Fullstack Web Apps gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack Web Apps, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack Web Apps include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Impara TypeScript con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Controllo degli accessi basato sui ruoli (RBAC)» è gratuita?
Sì — il testo completo di «Controllo degli accessi basato sui ruoli (RBAC)» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack Web Apps, passa a CoddyKit PRO. Il corso Next.js 15 Fullstack Web Apps include 4 lezioni in totale.
Cosa imparerò in «Controllo degli accessi basato sui ruoli (RBAC)»?
Modelli ruoli e autorizzazioni degli utenti, li memorizzi nella sessione e applichi i controlli dei ruoli tra Server Components, route handler e middleware in un’app Next.js 15. Eserciti Next.js 15 Fullstack Web Apps con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Next.js 15 Fullstack Web Apps?
Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack Web Apps su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Controllo degli accessi basato sui ruoli (RBAC)»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack Web Apps?
Sì. Ogni lezione Next.js 15 Fullstack Web Apps include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Integrazione di NextAuth.js
- Gestione delle sessioni e JWT
- Middleware e controllo degli accessi
- Controllo degli accessi basato sui ruoli (RBAC)