Docs/Features
Authentication
Define a RequestAuthentication config object and pass it to @withAuth.
import { RequestAuthentication } from 'alado';
import { DataStore } from '@data-store';
export const bearerAuth: RequestAuthentication = {
inputProperty: 'headers.x-api-key', // where to read the token from
outputProperty: 'auth.user', // where to write the result on req
handler(value: string) {
return DataStore.findUserByToken(value); // return user or null/undefined
},
error: {
statusCode: 401,
message: 'Unauthorized',
},
};Authentication is required unless you say otherwise.
requireddefaults totrue: a route with@withAuthrefuses every request without valid credentials witherror, also whenrequiredis left out. Only an explicitrequired: falselets requests through anonymously (see Optional auth below). Before 3.8.1 a missingrequiredmeant optional.
The inputProperty supports dot-notation and can point to any part of the request:
inputProperty |
Reads from |
|---|---|
headers.x-api-key |
Request header |
headers.authorization |
Authorization header |
query.api_token |
Query parameter |
body.token |
Request body field |
path.token |
Path parameter |
Header names are case-insensitive: headers.X-Api-Key and headers.x-api-key read the same header.
The resolved value from handler is set at outputProperty on the request object, making it available as req.auth.user in your handler.
What the handler receives
The value at inputProperty is checked before handler runs (the rest of the request is validated only after authentication):
- If the route declares a validator for that field (for example
tokenin thebodyDTO of@defineRequest), that validator decides. It runs only this once for the request: request validation reuses the result. Query and path values are converted for anumber()/bigint()validator here too. - Otherwise only a string is accepted.
handler gets the value as it was sent: a query or path value stays a string even when a number() validator converts it for req.query / req.path.
Anything else gets the configured error and handler is not called. This keeps an object from a JSON body ({ "token": { "$ne": null } }, a NoSQL operator) or an array from a repeated query key (?token=a&token=b) away from a handler that passes the value to a database.
Returning and throwing
handler should return the authenticated entity, or null/undefined for credentials it does not accept. A thrown error gets the client error (the exception text never reaches it); how it is logged depends on what was thrown:
- an error with a 4xx
statusCode(throw { statusCode: 401 }, or anErrorwithstatusCode: 401) is a refusal of the credentials and is logged only withverbose: true, like other client errors; - anything else is a failure of the handler (a database down, a bug) and is always logged with
logger.error.
Libraries that throw on a bad token, such as jwt.verify, need their error turned into one of the first two, or every request with a junk token writes an error to the log:
handler(token: string) {
try {
return jwt.verify(token, secret);
} catch {
return null; // or: throw { statusCode: 401 }
}
},When the body is read
When inputProperty reads a header, a query parameter or a path parameter, the request body is read only after authentication, and after access control unless a rule reads body.*. A refused request never has its body parsed; its connection is closed after the error response when the body is larger than maxBodySizeBytes or chunked. With inputProperty: 'body.*' the body is read first, as it has to be.
Optional auth
Set required: false, explicitly, for soft checking (leaving required out means true): missing or invalid credentials, or a handler that throws, leave the request anonymous (nothing at outputProperty) instead of refusing it. A thrown error is still logged.
export const optionalAuth: RequestAuthentication = {
required: false, // no 401 when the token is missing, invalid or the handler throws
inputProperty: 'headers.authorization',
outputProperty: 'auth.user',
handler: (token) => UserService.findByToken(token),
error: {
statusCode: 401,
message: 'Unauthorized',
},
};Several strategies
Since 3.9.0 @withAuth takes any number of arguments. Every argument is an alternative, and one passing alternative is enough. An array argument is a group: every strategy in it must pass.
import { allOf, withAuth } from 'alado';
@withAuth(bearerAuth, apiKeyAuth) // a bearer token OR an API key
@withAuth([apiKeyAuth, bearerAuth]) // an API key AND a bearer token
@withAuth(allOf(apiKeyAuth, bearerAuth)) // the same group, spelled out
@withAuth([apiKeyAuth, bearerAuth], shareLink) // (API key AND bearer token) OR a share link- Alternatives are tried in the order given; the first one that passes wins and the ones after it are not run (their handlers are not called). Inside a group, the first strategy that refuses ends the group.
- A missing credential moves on to the next alternative. So does a
handlerthat throws: the exception is logged and that strategy counts as refused. - Every strategy writes its result to its own
outputProperty, so the handler can tell which one let the request in (req.auth.userorreq.auth.client). Results are written only for the alternative that passed: a group that fails half-way leaves nothing inreq.auth. - When no alternative passes, the answer is the
errorof the first alternative whose credential was sent and refused ("invalid token" rather than "missing API key"), or, if no credential was sent at all, theerrorof the first alternative. - In a group, a
required: falsestrategy runs and writes its result when its credential is valid, but never fails the group:[apiKeyAuth, optionalBearerAuth]needs the API key and picks up the user when a token comes with it. - Alternatives made only of
required: falsestrategies let anonymous requests through. They cannot be mixed with alternatives that need credentials (those would never refuse anything): startup fails if they are. - An optional alternative that authenticates nobody (no credential, or one refused) does not end the search (3.9.1):
@withAuth(optionalBearerAuth, optionalApiKeyAuth)with only an API key is authenticated by the API key. When no alternative authenticates, the request goes on with the first alternative's result, as with a single optional strategy. - When any strategy reads
body.*, the body is read before authentication, and aGETroute with such a strategy fails at startup (BODY_NOT_ALLOWED).
Arrays and spreading.
@withAuth([a, b])needs both, but@withAuth(...[a, b])passesaandbas two alternatives and accepts either one: spreading a list turns AND into OR without any error. PreferallOf(a, b)for a group, and never spread a list into@withAuth.
Without decorators the same goes in Context.auth: one RequestAuthentication, or a list of alternatives in which a nested list is a group (auth: [[apiKeyAuth, bearerAuth], shareLink]). The list is checked when the route is registered: an empty list or group, a group inside a group, or the same strategy twice in one group fail at startup.
The OpenAPI document gets the same shape: every alternative is one entry of the operation's security, and the strategies of a group share one entry. See OpenAPI / Swagger.