Skip to content

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.

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.

@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 below
class 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 declaresResult
NothingInherits 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.

@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.

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() (or public: true);
  • @Auth({ optional: true }), for routes that work with or without a user.
RouteDefault (v4)With requireAuthByDefault: false (the 3.x behavior)
No decorator401 without a tokenPublic
@Public()PublicPublic
@Auth({ optional: true })Public, user available if sentSame
@Auth() / @Roles()ProtectedProtected

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: false to OpenAPIPlugin.
  • The GraphQL endpoint is public by default: one HTTP route serves every operation, so access belongs in the resolvers and the context factory. Pass public: false to GraphQLPlugin when 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 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 / @MinimumRole check, 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 by getUserRoles(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.

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.

Since v4.0.0, RBACPlugin registers only what you define:

new RBACPlugin({ roles }); // your roles, nothing else

Two 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
});
  • useDefaults adds five built-in roles alongside yours; they take part in inheritance. With no roles at all, the built-in set is still created, so new RBACPlugin() keeps working.
  • enableManagementRoutes registers /rbac/roles, /rbac/check-permission and 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.

  • requireAuthByDefault left on (it is by default) on AuthPlugin
  • @Public() on every intentionally open route — and nowhere else
  • Class-level @Roles / @Auth on controllers, method-level only for exceptions
  • resolveRoles if a user’s role depends on the tenant, project or organization being accessed
  • No useDefaults: true or enableManagementRoutes: true on RBACPlugin unless you use them
  • A schema on @Param for ids
  • @WebSocket(path, { auth: true }) on gateways