Microservices
Guards
Protect message handlers.
Guards, @Role and @Roles run on message handlers. The caller's identity cannot come from an HTTP header, so it rides in a message header:
// the caller
val client = ClientProxy(NatsClient("nats://nats:4222")) { codec }
client.headers["authorization"] = "Bearer " + serviceToken // sent with every message
// the service
@Injectable
class ServiceTokenGuard(private val jwt: JwtService) : Guard {
override suspend fun canActivate(ctx: ExecutionContext): Boolean {
val token = ctx.request.header("authorization")?.removePrefix("Bearer ") ?: throw UnauthorizedException("token required")
ctx.principal = jwt.principal(jwt.verify(token))
return true
}
}
@UseGuards(ServiceTokenGuard::class) @Role("ADMIN") @MessagePattern("admin.reset") fun reset() = "done"The handler's headers are the message's headers (or gRPC metadata), so a token can ride in a header and be checked by a guard exactly as for HTTP. A refused message gets an error reply (RpcException with status 401 or 403 on the caller).
Remember that anything that can publish to the broker can send messages: also secure the broker (credentials, network rules, TLS), and give each service only the topics it needs.