Guards and interceptors
A guard decides whether a request may continue. An interceptor wraps the handling of a request and can act before it, after it, or instead of it. Both are @Injectable() singletons created once at start-up, so neither may keep per-request data in a field.
Where the two sit among the other stages of a request is shown in How a request is handled. In short: interceptors of the application enter first, then the guards run, then the interceptors of the module, the controller and the handler, and all of them before the body is read.
Guards
A guard is a class with a canActivate(ctx) method.
canActivatereturnsbooleanorPromise<boolean>. A synchronous guard adds no promise to the request.- Only
truelets the request through.false, or any other value, answers 403 through the Forbidden responder. Throw anHttpExceptionfor any other status, as the guard above does for 401. - A guard reads the request through the request context: headers, cookies,
ctx.urlParams,ctx.queryandctx.route. URL parameters and the query are raw strings there and the body is not available, because validation comes after guards. - A guard may set response headers and cookies with
ctx.reply, for example rate-limit headers. - A guard passes what it learned, such as the current user, to later guards and to the handler through a context key.
A guard that returns false is the short form for "authenticated, but not allowed":
A complete token-based guard is built in Authentication with JWT. Exempting single routes from a module-wide guard is done with an attribute.
Attaching guards
- Guards run application first, then module, then controller, then handler. Within one level they run in the order given. Module guards include those inherited from importing modules, outermost first.
- A guard class that appears at more than one level runs once, at its first position.
- The first guard that denies or throws stops the request. Later guards do not run.
- On a class, place
@UseGuardsabove@Controlleror@Module. - Guards of the application, which also cover modules that plugins add, are the
guardsoption ofNaviosFactory.create.
A class listed as a guard must be @Injectable() and have a canActivate method, or init() fails.
Interceptors
An interceptor is a class with an intercept(ctx, next) method. Calling next() runs the rest of the pipeline: inner interceptors, validation and the handler, and for an interceptor of the application the guards as well.
next()resolves to theRouteResultof a successful request:{ status, body, kind, headers?, cookies? }. For a JSON response,bodyis the validated body, not yet serialised.next()may be called again, for example to retry. The request body is read once. A stream that is not sent in the end is closed.- When validation or the handler throws, or for an interceptor of the application a guard,
next()rejects with the original error. The error becomes a response only after the outermost interceptor has exited, so an interceptor sees failures as exceptions, never as 4xx or 5xx results. Rethrow the error unless you intend to replace the response. - An interceptor may return a different
RouteResult, areply()or aproblem().headersof a result win over those set withctx.reply, and their names may have any case. A result that cannot be sent, such as a status of 99, is a 500. - An interceptor may also answer without calling
next(). Nothing inside it runs then. The guards of the route have run already, unless it is an interceptor of the application, but it must not give one caller what only another one may see:
A real one also limits how many entries it keeps and for how long. Added with app.intercept it would run before the guards, and answer a caller whose access has been revoked since.
To act when the response has actually been sent, rather than when the handler has returned, register a callback with ctx.onFinish.
Attaching interceptors
Interceptors attach at four levels, outermost first:
- Interceptors of the application run around the guards; those of the other three levels run behind them. A class that is attached at both runs around them.
- Within one level the first interceptor given is the outermost.
- An interceptor class that appears at more than one level runs once.
app.intercept()must be called beforeinit().- An interceptor does not run for a request that matches no route.