Access Control
Access Control
Section titled “Access Control”Authentication & Authorization covers the plugins and the per-route decorators. This guide is about making protection the thing you get by default, so that a forgotten decorator cannot publish a route.
The problem with opt-in protection
Section titled “The problem with opt-in protection”A route with no access decorator is public. That is convenient for a hello-world and dangerous in an application with a hundred routes: forgetting @Auth() on one of them fails silently — the route works, tests pass, and it answers anonymous requests.
Three tools remove that failure mode. Use them together.
1. Protect a whole controller
Section titled “1. Protect a whole controller”@Auth, @Roles, @Permissions and @MinimumRole can decorate a class. The rule then applies to every route in it.
import { Controller, Get, Post, Delete, Roles, Public } from 'veloce-ts';
@Controller('/orders')@Roles(['member']) // default for every route belowclass OrdersController { @Get('/') // requires `member` list() {}
@Delete('/:id') @Roles(['admin']) // a method-level decorator of the same kind replaces the class one remove() {}
@Get('/status') @Public() // the explicit exception status() { return { ok: true }; }}How the two levels combine:
| Method declares | Result |
|---|---|
| Nothing | Inherits every rule from the class |
@Roles([...]) | Its roles replace the class-level roles; a class-level @Auth still applies |
@Public() | Inherits nothing: the route is open |
A subclass inherits the class-level rules of its base controller.
2. Mark public routes explicitly
Section titled “2. Mark public routes explicitly”@Public() says “this route is open on purpose”. It works on a method or on a whole controller, and has a functional-API equivalent:
@Controller('/webhooks')@Public()class WebhooksController { /* signature-verified inside the handlers */ }
app.get('/health', { handler: () => ({ ok: true }), public: true });On its own @Public() changes nothing for a route that had no decorator — it documents intent. It becomes load-bearing with the next option.
3. Deny by default
Section titled “3. Deny by default”import { AuthPlugin } from 'veloce-ts';
app.usePlugin(new AuthPlugin({ jwt: { secret: process.env.JWT_SECRET! }, userProvider,}));Since v4.0.0 that is all it takes: with AuthPlugin installed, a route that declares nothing requires a valid access token. Only two things opt a route out:
@Public()(orpublic: true);@Auth({ optional: true }), for routes that work with or without a user.
| Route | Default (v4) | With requireAuthByDefault: false (the 3.x behavior) |
|---|---|---|
| No decorator | 401 without a token | Public |
@Public() | Public | Public |
@Auth({ optional: true }) | Public, user available if sent | Same |
@Auth() / @Roles() | Protected | Protected |
What it covers:
- Every route in the registry, including the ones other plugins add (RBAC management, your own plugins) and routes registered by plugins installed after
AuthPlugin. - The framework’s own login, refresh, register, logout, OAuth, session, health and documentation routes are already marked public. To put the API docs behind authentication as well, pass
public: falsetoOpenAPIPlugin. - The GraphQL endpoint is public by default: one HTTP route serves every operation, so access belongs in the resolvers and the
contextfactory. Passpublic: falsetoGraphQLPluginwhen every operation needs a token. - A route that authenticates by its own means — a webhook signature, an API key checked in the handler — needs
public: true, or the token guard rejects the request before your check runs. - Not WebSocket gateways — they are not HTTP routes in the registry. Declare their access with
@WebSocket(path, { auth: true }).
Roles that depend on the request
Section titled “Roles that depend on the request”@Roles reads the roles claim of the access token. That is correct when a user has one set of roles. It is wrong when the same user holds different roles in different organizations and the organization is chosen per request — a header, a subdomain, a path segment. @Roles(['admin']) would then accept a user who is an admin somewhere else.
resolveRoles replaces the token’s roles with roles computed for the request:
import { RBACPlugin, ForbiddenException } from 'veloce-ts';
app.usePlugin(new RBACPlugin({ roles, resolveRoles: async (c, user) => { const member = await findMembership(user.sub, c.req.header('X-Org-ID')); if (!member) throw new ForbiddenException('Not a member of this organization'); return [member.role]; },}));- It runs in the route guard: after authentication, before any
@Roles/@Permissions/@MinimumRolecheck, and only for routes that carry one of those. - Its result is used by all three decorators, stored in the context as
rbac.roles, and returned bygetUserRoles(c). - Throw an HTTP exception to reject the request.
- It is not called for anonymous requests; those get a 401 first.
The Multi-tenancy guide builds a complete setup on top of it.
Validate path parameters
Section titled “Validate path parameters”A malformed id should be rejected before it reaches your database. @Param accepts a Zod schema:
import { z } from 'zod';
@Get('/:id')getOrder(@Param('id', z.string().uuid()) id: string) {}
// Or validate — and coerce — all of them at once@Get('/:year/:month')archive( @Param(z.object({ year: z.coerce.number().int(), month: z.coerce.number().int().min(1).max(12) })) period: { year: number; month: number },) {}A value that fails validation is a 422 with the usual violations list. Without a schema @Param behaves as before.
RBAC defaults
Section titled “RBAC defaults”Since v4.0.0, RBACPlugin registers only what you define:
new RBACPlugin({ roles }); // your roles, nothing elseTwo options bring back what 3.x did by default:
new RBACPlugin({ roles, useDefaults: true, // also create guest / user / moderator / admin / super-admin enableManagementRoutes: true, // register the seven /rbac/* routes});useDefaultsadds five built-in roles alongside yours; they take part in inheritance. With norolesat all, the built-in set is still created, sonew RBACPlugin()keeps working.enableManagementRoutesregisters/rbac/roles,/rbac/check-permissionand five more routes, reachable by any authenticated user; they describe your role model. Turn it on only if you use them.
If a decorator names a built-in role — @Roles(['admin']) — and you pass your own roles, define admin yourself.
Checklist
Section titled “Checklist”-
requireAuthByDefaultleft on (it is by default) onAuthPlugin -
@Public()on every intentionally open route — and nowhere else - Class-level
@Roles/@Authon controllers, method-level only for exceptions -
resolveRolesif a user’s role depends on the tenant, project or organization being accessed - No
useDefaults: trueorenableManagementRoutes: trueonRBACPluginunless you use them - A schema on
@Paramfor ids -
@WebSocket(path, { auth: true })on gateways
Related
Section titled “Related”- Authentication & Authorization
- Multi-tenancy
- Middleware — running your own code after authentication
- WebSockets