Fundamentals
Execution context
What a guard, interceptor or filter knows about the call in progress.
Guards, interceptors and exception filters do not know in advance which endpoint they protect, so they receive an ExecutionContext: a description of the call in progress.
| Member | Meaning |
|---|---|
request | the HttpRequest (method, path, query, headers, body); for messages and gRPC, headers carry the message headers or metadata |
principal | the authenticated caller, set by an authentication guard (read and write) |
controller, handler | the controller class and the name of the method being called |
annotation<A>() | an annotation of type A on the handler, else on the controller (NestJS getAllAndOverride) |
handlerMetadata, classMetadata | all annotations of the handler and of the controller |
http | the HttpContext: request-scoped providers, path parameters, response headers and cookies |
One guard for many endpoints
The power of the context is that one guard can apply a policy driven by annotations on each endpoint:
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) @Metadata
annotation class RequiresReason(val text: String)
@Injectable
class AuditGuard(private val audit: AuditLog) : Guard {
override suspend fun canActivate(ctx: ExecutionContext): Boolean {
val reason = ctx.annotation<RequiresReason>()?.text // @RequiresReason("...") on the handler or its controller
?: return true // no annotation: nothing to check
audit.record(ctx.principal?.id, "${ctx.controller.simpleName}.${ctx.handler}", reason)
return true
}
}
@Controller("/payments") @UseGuards(AuditGuard::class)
class PaymentsController {
@RequiresReason("refund requested by support") @Post("/{id}/refund") fun refund(@Param id: String) = ...
@Get("/{id}") fun find(@Param id: String) = ... // not audited
}annotation<A>() looks at the handler first, then the controller, so a method can override a class-wide setting. Annotations are generated by the processor at build time, so reading them costs nothing per request. Your own annotations become readable this way when marked @Metadata (Custom decorators).
One shape for every transport
The same context is used for HTTP, microservice, WebSocket and gRPC handlers, so a guard or interceptor you write once works on all of them. For a message handler the "headers" are the message headers; for a WebSocket handler the "request" is the connection's handshake.
Setting the principal
ctx.principal = SimplePrincipal("u-1", setOf("admin")) // after you authenticated; later guards and the handler can use it