fastify-xauth-jwks
requireRole
Fastify preHandler factory that replies 403 if the authenticated user lacks the required role.
requireRole
Create a Fastify preHandler hook that enforces role-based access control. Returns 403 Forbidden if the authenticated user's roles claim does not include at least one of the specified roles.
Signature
import { requireRole } from "@xenterprises/fastify-xauth-jwks/utils";
requireRole(roles: string | string[]): FastifyPreHandlerHook
Params
| Name | Type | Required | Description |
|---|---|---|---|
roles | string | string[] | Yes | Role name or array of role names. The user must have at least one of the specified roles. |
Returns
An async Fastify preHandler hook (request, reply) => Promise<void>. Replies with 403 { error: "Forbidden", message: "Insufficient permissions" } if the check fails.
Throws
Does not throw at call time. The returned handler does not throw — it replies with 403 instead.
Examples
Basic — protect a single route
import { requireRole } from "@xenterprises/fastify-xauth-jwks/utils";
fastify.delete("/admin/users/:id", {
preHandler: requireRole("admin"),
handler: async (request) => {
await db.users.delete(request.params.id);
return { deleted: true };
},
});
Realistic — allow multiple roles and chain with other hooks
import { requireRole, requireEndpoint } from "@xenterprises/fastify-xauth-jwks/utils";
fastify.get("/admin/billing", {
preHandler: [
requireEndpoint("admin"), // must be authenticated via the admin path
requireRole(["admin", "billing"]), // must have admin or billing role
],
handler: async (request) => {
return db.billing.getSummary(request.auth.userId);
},
});
See Also
- hasRole — Underlying check used by this factory
- requirePermission — Similar factory for fine-grained permission claims
- requireEndpoint — Enforce which auth path authenticated the request
AI Context
package: "@xenterprises/fastify-xauth-jwks"
import: requireRole from "@xenterprises/fastify-xauth-jwks/utils"
use-when: Fastify preHandler factory that returns 403 if the JWT payload lacks the specified role
usage: { preHandler: [requireRole(['admin'])] }
