WebSockets
Guards
Control who may use a gateway.
Guards, pipes, interceptors and exception filters work on gateway handlers (@SubscribeMessage) the same way as on HTTP routes: the same classes, attached with the same annotations. A guard decides whether a caller may use a handler.
@Injectable
class QueryTokenGuard(private val jwt: JwtService) : Guard {
override suspend fun canActivate(ctx: ExecutionContext): Boolean {
val token = ctx.request.query["token"]?.firstOrNull() ?: throw UnauthorizedException("token required")
ctx.principal = jwt.principal(jwt.verify(token)) // a JwtException is a refusal
return true
}
}
@WebSocketGateway("/secure") @UseGuards(QueryTokenGuard::class) // ws://host/secure?token=...
class SecureGateway {
@SubscribeMessage("whoami") fun whoami(): String = "hello"
@Role("ADMIN") @SubscribeMessage("admin") fun admin(): String = "admin ok" // roles work too
}What the guard sees
For these handlers the "request" is the connection's handshake: its query string, headers and cookies. So a token passed as ?token=..., in a cookie or in Authorization can be checked. The ExecutionContext is the same shape as for HTTP, so a guard written once works for controllers, gateways and message handlers.
When it runs
A guard runs for each message, before the handler. A refused message gets an exception reply to that client ({ "status": 401, "message": "..." }); the connection stays open. To refuse the connection itself (a client with no valid token should not stay connected), check in handleConnection:
override fun handleConnection(client: WsClient) {
val ok = client.request.query["token"]?.firstOrNull()?.let { runCatching { jwt.verify(it) }.isSuccess } == true
if (!ok) client.close(4401, "unauthorized") // 4000-4999 are free for applications
}Do both: refuse bad connections early, and guard handlers for roles.
Tested
A guard on a gateway (a refused message and a role check) is tested. Interceptors and exception filters use the same pipeline but have fewer WebSocket-specific tests; check your case.