Authentication
Sign and validate JWT tokens, protect routes with authentication decorators, and manage server-side cookie authentication in AntelopeJS.
Prerequisites
Install the @antelopejs/interface-auth package in your module, and import the authentication functions from it.
The task API flow validates the token before the controller runs. Authorization inside the application is a separate check.
The @antelopejs/interface-auth package signs and validates tokens. The @antelopejs/interface-api package provides the controller and route decorators that protected endpoints use.
Configure an auth provider, such as @antelopejs/auth-jwt with config.secret, and an API provider in your project. The interface packages alone contain no implementation. See the combined configuration.
Authentication is not authorization
Authentication tells you which claims a valid token carries. Your application still decides which records and actions those claims permit. @Authentication() does not filter queries by userId, block writes to another account, or validate a request body.
For a first check, protect one read-only route. Call it without a token, then call it with a token you signed. Verify that the server rejects the first request and that the second returns only the public fields you intend. Never return password hashes or signing keys.
Signing tokens
The SignRaw function creates a signed JWT from a payload. ValidateRaw verifies the token later. An optional second argument sets when the token expires and when it becomes valid.
import { SignRaw } from "@antelopejs/interface-auth";
const token = await SignRaw(
{ userId: "123", role: "admin" },
{ expiresIn: "24h" },
);
The options object supports these fields:
| Option | Description |
|---|---|
expiresIn | Time until the token expires, in seconds or as a timespan string such as "1h", "7d", or "30m" |
notBefore | Time before the token becomes valid, in seconds or as a timespan string |
Set expiresIn on every session token. A token without expiration stays valid until you rotate the signing key.
Validating tokens
The ValidateRaw function verifies a token's signature and returns the decoded payload. The promise rejects when the token is missing, invalid, expired, or not yet valid. The @antelopejs/auth-jwt provider rejects with an HTTPResult: 401 Unauthorized when there is no token, and 403 with the reason when verification fails.
import { ValidateRaw } from "@antelopejs/interface-auth";
const payload = await ValidateRaw(token);
// payload: { userId: "123", role: "admin", iat: ..., exp: ... }
The payload holds the original data plus the standard JWT claims iat (issued at) and exp (expiration). Its type is AuthClaims, a string or a JSON object, and the interface does not check its shape. An optional second argument sets validation options.
| Option | Description |
|---|---|
ignoreExpiration | Accept expired tokens |
ignoreNotBefore | Accept tokens before their notBefore time |
maxAge | Maximum age of the token, in seconds or as a timespan string |
Pass these options as the second argument to ValidateRaw:
// Exceptional validation policy; this alone is not a refresh flow
const payload = await ValidateRaw(token, { ignoreExpiration: true });
Do not use ignoreExpiration for ordinary requests. A refresh endpoint needs its own credential lifetime, revocation, and replay policy. If it accepted an expired access token alone, a client could renew forever.
Protecting routes with @Authentication
The @Authentication parameter decorator reads the token from the request, validates it, and passes the decoded payload to the handler. It reads the raw token from the x-antelopejs-auth header. Only when that header is absent does it read the ANTELOPEJS_AUTH cookie. It does not read the Authorization header.
import { Controller, Get } from "@antelopejs/interface-api";
import { Authentication } from "@antelopejs/interface-auth";
class ProfileController extends Controller("/api/profile") {
@Get("me")
async getProfile(@Authentication() auth: any) {
return { userId: auth.userId, role: auth.role };
}
}
The handler runs only when validation succeeds. Otherwise the server answers with the rejection from the auth provider. With @antelopejs/auth-jwt, that is 401 for a missing token and 403 for an invalid one.
Server-side cookie authentication
The SignServerResponse function signs a token and sets it as the ANTELOPEJS_AUTH cookie on the response. It replaces any Set-Cookie header already set, and it does not send or end the response. Choose this transport only after you decide your cookie and CSRF policy. The helper adds no cookie attributes by default, so HttpOnly, Secure, and SameSite are all off unless you pass them.
This example assumes a validateCredentials function from your application. The cookie needs HTTPS because secure is on. For the local HTTP tutorial, use the header-based flow.
import {
Controller,
Post,
JSONBody,
Context,
type RequestContext,
} from "@antelopejs/interface-api";
import { SignServerResponse } from "@antelopejs/interface-auth";
class AuthController extends Controller("/api/auth") {
@Post("login")
async login(
@JSONBody() body: { email: string; password: string },
@Context() ctx: RequestContext,
) {
const user = await validateCredentials(body.email, body.password);
await SignServerResponse(
ctx.rawResponse,
{ userId: user.id, role: user.role },
{ expiresIn: "7d" },
{ httpOnly: true, secure: true, path: "/" },
);
return { success: true };
}
}
The function accepts four arguments:
| Argument | Description |
|---|---|
res | The raw ServerResponse object (ctx.rawResponse from the request context) |
data | The payload to encode in the token |
signOptions | Token signing options (same as SignRaw) |
cookieOptions | Optional CookieOptions: path, domain, secure, httpOnly, expires, maxAge, and signed |
The browser sends the cookie with later requests. The @Authentication decorator reads the ANTELOPEJS_AUTH cookie when the request has no x-antelopejs-auth header.
The helper writes each CookieOptions key as is. maxAge becomes maxAge, not the standard Max-Age attribute. signed becomes a bare directive and adds no signature. expires uses String(date), not an HTTP date.
Whether the browser sends the cookie also depends on the request origin and the credentials settings. Before you accept writes authenticated by cookie, configure an explicit SameSite policy and CSRF protection in your HTTP integration. The CookieOptions type has no sameSite field, so the helper never sets it. Token expiry and cookie expiry are separate settings.
Custom auth decorators
The CreateAuthDecorator function builds an authentication decorator with your own token source, verification, and validation. Use it for role-based access control or multi-tenant authentication.
import { HTTPResult } from "@antelopejs/interface-api";
import { CreateAuthDecorator, ValidateRaw } from "@antelopejs/interface-auth";
import type { IncomingMessage, ServerResponse } from "node:http";
const AdminAuth = CreateAuthDecorator({
source(req: IncomingMessage, _res: ServerResponse) {
const header = req.headers["authorization"];
return typeof header === "string"
? header.replace("Bearer ", "")
: undefined;
},
async authenticator(token?: string) {
const payload = await ValidateRaw(token);
if (typeof payload === "string" || payload.role !== "admin") {
throw new HTTPResult(403, "Admin access required");
}
return payload;
},
});
export { AdminAuth };
ValidateRaw returns AuthClaims, a string or a JSON object. The typeof check rules out the string, so TypeScript lets the code read payload.role. The authenticator throws an HTTPResult so the client gets 403. The API provider answers any other thrown value with 500.
The callbacks object takes four optional fields, which run in this order:
source(req, res)extracts the token from the request. The default readsx-antelopejs-auth, then theANTELOPEJS_AUTHcookie.authenticator(token, authenticatorOptions)verifies the token. The default isValidateRaw.authenticatorOptionsholds theVerifyOptionspassed to the authenticator.validator(data)checks the verified data. It must throw to deny access, and the handler receives its return value. A validator passed to the decorator call replaces the configured one.
Use the custom decorator on a route handler the same way as @Authentication.
import { Controller, Get } from "@antelopejs/interface-api";
import { AdminAuth } from "../auth/admin-auth";
class AdminController extends Controller("/api/admin") {
@Get("dashboard")
async dashboard(@AdminAuth() auth: any) {
return { message: "Welcome, admin", userId: auth.userId };
}
}
Only requests with a valid admin token reach this handler. The role check lives in the decorator, so the handler holds only business logic.
Authentication flow
A typical authentication flow combines token signing, cookie handling, and route protection.
User registers or logs in
The server validates credentials and issues a signed token. The server returns the token in the response body or sets it as a cookie.
Client sends the token with requests
The client includes the token in the x-antelopejs-auth header, or the browser sends it automatically as the ANTELOPEJS_AUTH cookie.
Route handlers validate the token
The @Authentication decorator reads and validates the token before the handler runs. A missing or invalid token gets an error response.
Token expires
Reject expired access tokens. Require the user to authenticate again, or implement a separately designed refresh-credential flow. The interface does not supply a complete session renewal policy.
Controllers declare which routes need authentication through decorators. The auth interface and its provider do the signing and validation, so that code stays out of your business logic.