Introduction
Guards
Decide whether a caller may use an endpoint.
A guard answers one question about a request: "may this caller use this endpoint?" It runs after the route is found and before anything else touches the request (before interceptors, pipes and your code). If the answer is no, your handler never runs.
Write one
@Injectable
class ApiKeyGuard(private val keys: KeyService) : Guard {
override suspend fun canActivate(ctx: ExecutionContext): Boolean {
if (ctx.annotation<Public>() != null) return true // an endpoint marked @Public is open
val key = ctx.request.header("x-api-key") ?: throw UnauthorizedException("Missing API key")
ctx.principal = keys.principalFor(key) ?: throw UnauthorizedException("Unknown API key")
return true
}
}- 401 Unauthorized means "I do not know who you are": throw
UnauthorizedException. - 403 Forbidden means "I know who you are, and you may not": throw
ForbiddenException, or returnfalse. - A guard is a normal provider: it can take services in its constructor (here
KeyService), and it can read the request.
Attach it
@Controller("/reports") @UseGuards(ApiKeyGuard::class) // every route of the controller
class ReportsController {
@Get fun all() = ... // needs the API key
@Get("/{id}") @UseGuards(AdminGuard::class) fun one(@Param id: String) = ... // and this one also AdminGuard
}
app.http(adapter) { useGuards(ApiKeyGuard::class) } // every route of the applicationGuards stack: global ones run first, then the controller's, then the handler's, and all must allow.
Pass information on: the principal
When a guard has worked out who the caller is, store it: ctx.principal = .... Later guards, the handler and filters can use it. A handler gets it by declaring a parameter of the principal type:
@Get("/me") fun me(user: JwtPrincipal): Profile = profiles.of(user.id) // the caller, set by a guardOne guard, many routes: reading annotations
A guard sees the annotations of the handler and its controller, so one guard can implement a whole policy:
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) annotation class Public
@Controller("/shop") @UseGuards(ApiKeyGuard::class)
class ShopController {
@Public @Get("/catalog") fun catalog() = ... // the guard returns true for this one
@Get("/orders") fun orders() = ... // needs a key
}ctx.annotation<T>() finds an annotation on the handler first, then the controller; ctx.handlerMetadata and ctx.classMetadata list them all.
Ready-made guards
| Guard | For |
|---|---|
@Authenticated | the caller must be signed in (Authentication) |
@Role / @Roles("admin") | the caller must have a role (Authorization) |
ThrottlerGuard | rate limiting (Rate limiting) |
WebhookGuard | verify a signed incoming webhook (Webhooks) |
Guards run on WebSocket, microservice and gRPC handlers too, so one policy covers every way into your application.
Guard or middleware?
A guard knows which endpoint is being called and its annotations, so it is the right place for permission rules. Middleware does not know the route: use it for request-wide things like CORS or request ids (Middleware).
Good practice
- Fail closed. If a guard cannot decide (a database error), it should refuse, not allow.
- Do authentication (who are you?) in one guard and authorization (may you?) in another or via
@Roles; keep each small. - Never rely on hiding an endpoint: guard it.
- Test a guard by calling
canActivatewith a fake context, and test the endpoint end to end withTestServerincluding the refused cases (401 and 403).