Authentication
The authentication decorators, `authenticateRequestUser`, and the token input they share.
Overview
Authentication turns an incoming HTTP request into a User row. @antelopejs/interface-dms/auth exports one plain function, authenticateRequestUser, and four decorators: AuthRawUser, AuthUser, IfAuthUser and AuthOwnerOnly. Each of them binds the verified user and tenant to the request, and getRequestTenantId then returns that tenant.
All of them read the bearer token from the Authorization header of the request (Authorization: Bearer <token>) and run the same two steps:
- The authenticator decodes the token into a
TenantTokenInput: the user id, the tenant id, and the undecoded token itself. - The validator loads the user named by that id and verifies the token against that user. It checks the signature, checks that the token was issued as an access token, and checks that the session the token names still exists. It then applies the extra requirement of the decorator.
The decorator injects whatever the validator returns. The four decorators differ only in the requirement they enforce and in what they do when it fails.
The User type they inject comes from @antelopejs/interface-dms/auth/db and is described in Users. The generators in Tokens and sessions produce the tokens they consume.
Require an authenticated user
AuthUser injects the User, and enforces email validation when the deployment sets auth.mustValidateEmail. A caller whose email is not validated then gets 401 ($dms.refusals.auth.email_not_validated). A token that is malformed, names no existing user, is badly signed, expired or issued for another purpose gets 401 ($dms.refusals.auth.invalid_session_token) whatever the reason, so a forged token cannot tell whether its id names a user. A token whose session was signed out gets 401 (error.session_expired). Use it on any route that must have a signed-in caller.
import { Controller, Get } from "@antelopejs/interface-api";
import { AuthUser } from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";
export class ProfileController extends Controller("/api/profile") {
@Get("")
getProfile(@AuthUser() user: User): { id: string; email: string } {
// 401 before the handler runs when the token is missing or invalid
return { id: user._id, email: user.email };
}
}
The injected value is the full User row, including fields you must not return over HTTP. Pass it through sanitizeUser before you serialize it, as described in Users.
Skip the email-validation gate
AuthRawUser resolves the same User but does not apply the email-validation requirement. The routes that exist because the email is not validated yet use it: reading the current account, logging out, and requesting a new validation email. Modules also use it to gate their own API routes on a signed-in caller.
import { Controller, Get, Post } from "@antelopejs/interface-api";
import {
AuthRawUser,
sendEmailValidationEmail,
} from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";
export class AccountController extends Controller("/api/account") {
@Get("/me")
me(@AuthRawUser() user: User): { email: string; isValidated: boolean } {
return { email: user.email, isValidated: user.isValidated };
}
@Post("/resend-validation")
async resendValidation(@AuthRawUser() user: User): Promise<{ sent: true }> {
// reachable while user.isValidated is still false
await sendEmailValidationEmail(user);
return { sent: true };
}
}
Both decorators inject the raw database row, and neither strips sensitive fields. "Raw" refers to the skipped email-validation step, not to the shape of the object.
Accept anonymous callers
IfAuthUser is the optional variant. It injects User | undefined and does not reject the request. A missing token, a malformed token, and a token that fails validation all resolve to undefined.
import { Controller, Get } from "@antelopejs/interface-api";
import { IfAuthUser } from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";
export class ArticleController extends Controller("/api/articles") {
@Get("")
list(@IfAuthUser() user: User | undefined) {
// a missing, malformed or expired token all land here as `undefined`
return user
? { scope: "member", readerId: user._id }
: { scope: "anonymous" };
}
}
An expired token resolves to undefined, not to a 401. A client-side refresh interceptor that reacts to 401 responses therefore does not fire on a route guarded this way. When a route must fail on an expired session, guard it with AuthUser and give the anonymous path its own route.
Restrict a route to platform owners
AuthOwnerOnly requires the authenticated user to be a platform owner (User.owner === true). It answers 401 when no token is provided and 403 ($dms.refusals.auth.owner_only) when the caller is authenticated but not an owner. The DMS applies it to the pages a module declares (/modules/<id>/...), which are owner-only administration spaces, unless the page is public or declares authOnly.
import { Controller, Get } from "@antelopejs/interface-api";
import { AuthOwnerOnly } from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";
export class MaintenanceController extends Controller("/api/maintenance") {
private jobs: string[] = ["reindex", "purge-sessions"];
@Get("/jobs")
listJobs(@AuthOwnerOnly() owner: User) {
// only reached when owner.owner === true
return { requestedBy: owner.email, jobs: this.jobs };
}
}
AuthOwnerOnly is a plain function that returns a decorator ready to apply, so you write @AuthOwnerOnly() like the three decorator factories above. It takes no arguments, because it supplies its own validator.
Gate every route on a controller
AuthRawUser, AuthUser and IfAuthUser apply to a parameter, to a property, or to the controller class itself. A property provider is a computed property of the controller. It is resolved on every request the controller handles, whether or not the handler reads it. A decorated property therefore gates the whole controller and gives the handlers a typed this.user.
import { Controller, Get, JSONBody, Post } from "@antelopejs/interface-api";
import { AuthUser } from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";
interface Settings {
theme: string;
}
export class SettingsController extends Controller("/api/settings") {
@AuthUser()
declare user: User;
private settings: Record<string, Settings> = {};
@Get("")
read(): Settings {
return this.settings[this.user._id] ?? { theme: "light" };
}
@Post("")
write(@JSONBody() body: Settings): Settings {
// also authenticated: the provider ran before the handler
this.settings[this.user._id] = body;
return body;
}
}
The DMS uses this form when it wires authentication onto a page controller. It applies the decorator to the user property of the page class.
Read the token payload
TenantTokenInput is the value the authenticator step produces and the validator step consumes. It is exported from @antelopejs/interface-dms/auth.
export interface TenantTokenInput {
tenantId: string;
id: string;
rawToken: string;
}
| Field | Type | Description |
|---|---|---|
tenantId | string | The tenant the token was issued for, taken from the tenantId claim of the token. |
id | string | The _id of the user the token was issued for. |
rawToken | string | The undecoded bearer token, used to verify the signature against the user. |
The decoded payload carries no signature guarantee on its own. The validator is the step that verifies rawToken against the user it names.
Authenticate inside a custom provider
authenticateRequestUser runs the same authenticator and validator outside a decorator. Use it when you write your own parameter provider and need the user and something else in one place.
authenticateRequestUser(ctx: RequestContext): Promise<User>
| Parameter | Description |
|---|---|
ctx | The request context handed to a parameter provider, from @antelopejs/interface-api. The function reads ctx.rawRequest.headers.authorization. |
It runs the same validation as AuthUser, so the email-validation gate applies. A caller whose email is not validated is rejected when the deployment requires validation. Every failure throws an HTTPResult with status 401. It also throws 401 when the request is already bound to another user or tenant.
import {
HTTPResult,
type RequestContext,
SetParameterProvider,
} from "@antelopejs/interface-api";
import { MakeParameterAndPropertyDecorator } from "@antelopejs/interface-core/decorators";
import { authenticateRequestUser } from "@antelopejs/interface-dms/auth";
const FORBIDDEN = 403;
export const AuthBetaTester = MakeParameterAndPropertyDecorator(
(target, key, index) => {
SetParameterProvider(target, key, index, async (ctx: RequestContext) => {
const user = await authenticateRequestUser(ctx);
if (!user.email.endsWith("@example.com")) {
throw new HTTPResult(FORBIDDEN, "Beta testers only");
}
return user;
});
},
);
The DMS builds its tenant guards the same way. AuthTenantOwner and AuthTenantMember in @antelopejs/interface-dms/guards authenticate the request, then resolve its tenant and check the caller's membership.
A provider is also the way to add a requirement and keep the built-in one. A call site can pass a replacement validator, as in @AuthUser(callback). That callback replaces the whole validation step, signature check included, and its return type is boolean | User. Such a call binds no tenant to the request. This interface exports no token-verification function, so a replacement validator cannot redo the signature check it removes.
Accept another credential family
@antelopejs/interface-dms/auth also exports the RequestPrincipal and RequestAuthenticator types. A RequestAuthenticator lets one route accept a credential that is not a DMS JWT. The decorators on this page accept only the DMS JWT. To accept another credential, pass authenticators to authenticateTenantRequest in @antelopejs/interface-dms/guards, through its authenticators option.
interface RequestPrincipal {
user: User;
tenantId: string;
}
interface RequestAuthenticator {
recognizes(token: string): boolean;
authenticate(token: string): Promise<RequestPrincipal>;
}
| Member | Contract |
|---|---|
recognizes | Claims the credential family from the bearer token, without trusting its contents. It must also recognize a malformed credential of its own family. |
authenticate | Verifies the credential and reloads its user. It throws on an invalid, expired or revoked credential. |
A token that no authenticator recognizes falls back to the DMS JWT. A token that two authenticators recognize is refused with 401. A principal is identity and tenant established together. It is not an authorization.
Bind a credential that has no user
A RequestAuthenticator answers a User. A machine token, a deploy key, or a token issued to a development environment has none. A guard that accepts such a credential verifies the credential itself, then calls bindVerifiedRequestIdentity. getRequestTenantId then returns the tenant of that credential.
interface VerifiedRequestIdentity {
id: string;
tenantId: string;
}
bindVerifiedRequestIdentity(ctx: RequestContext, identity: VerifiedRequestIdentity): void
| Field | Contract |
|---|---|
id | The caller the credential stands for, in a form that no User._id takes, such as environment:<id>. The DMS compares it with the identity the request already carries and reads nothing else from it. |
tenantId | The tenant the credential was issued for. Read it from the stored record of the credential, never from the request. |
Call it only after the credential in the Authorization header passed every check that makes it valid: its secret or signature, its expiry, and its revocation. The DMS trusts both fields as given.
The call grants nothing. It checks no membership, no permission, and no tenant access gate. The guard that calls it keeps those checks. For a credential that stands for a User, pass a RequestAuthenticator to authenticateTenantRequest instead. That function reloads the user and checks the membership.
import {
HTTPResult,
type RequestContext,
SetParameterProvider,
} from "@antelopejs/interface-api";
import { MakeParameterAndPropertyDecorator } from "@antelopejs/interface-core/decorators";
import { bindVerifiedRequestIdentity } from "@antelopejs/interface-dms/auth";
const UNAUTHORIZED = 401;
const BEARER = /^Bearer\s+(\S+)$/i;
interface DeployKey {
id: string;
tenantId: string;
}
/** Your own check of the secret, the expiry and the revocation. */
declare function verifyDeployKey(token: string): Promise<DeployKey | undefined>;
export const AuthDeployKey = MakeParameterAndPropertyDecorator(
(target, key, index) => {
SetParameterProvider(target, key, index, async (ctx: RequestContext) => {
const token = ctx.rawRequest.headers.authorization?.match(BEARER)?.[1];
const deployKey = token ? await verifyDeployKey(token) : undefined;
if (!deployKey) throw new HTTPResult(UNAUTHORIZED, "Unauthorized");
// both fields come from the verified key, not from the request
bindVerifiedRequestIdentity(ctx, {
id: `deploy-key:${deployKey.id}`,
tenantId: deployKey.tenantId,
});
return deployKey;
});
},
);
The call throws HTTPResult(401) in these cases:
- The identity has no
idor notenantId. - The request already carries another identity or another tenant.
- The authentication of the request failed, or a provider already read the request as anonymous.
- The
Authorizationheader changed after the request was bound.
A provider resolved alongside the guard, such as TenantScopedModel, does not wait for this call. Read the tenant in the handler with getRequestTenantId.
Decorator reference
| Decorator | Injects | Email validation | On failure |
|---|---|---|---|
AuthRawUser() | User | Not checked | 401 |
AuthUser() | User | Enforced when the configuration requires it | 401 |
IfAuthUser() | User | undefined | Enforced when the configuration requires it | Resolves to undefined |
AuthOwnerOnly() | User | Enforced when the configuration requires it | 401 without a valid token, 403 when not an owner |
Next steps
Continue with Tokens and sessions to see how the DMS issues and validates the tokens these decorators consume.