BoardKitBackend
BoardAuthGuard
Abstract authentication interface for HTTP and WebSocket requests
BoardAuthGuard is the abstract class that consumers implement to authenticate users for both REST API requests and WebSocket connections.
interface AuthenticatedUser {
userId: string;
displayName: string;
}
abstract class BoardAuthGuard {
abstract validateConnection(token: string): Promise<AuthenticatedUser | null>;
abstract validateRequest(token: string): Promise<AuthenticatedUser | null>;
}Methods
validateConnection
Validates a token from a WebSocket connection (the token field in JoinMessage). Returns the authenticated user, or null to reject the connection.
validateRequest
Validates a Bearer token from an HTTP request's Authorization header. Returns the authenticated user, or null to reject the request.
Implementation Example
import { BoardAuthGuard, type AuthenticatedUser } from '@hfu.digital/boardkit-nestjs';
import { verify } from 'jsonwebtoken';
class JwtAuthGuard extends BoardAuthGuard {
async validateConnection(token: string): Promise<AuthenticatedUser | null> {
return this.verifyToken(token);
}
async validateRequest(token: string): Promise<AuthenticatedUser | null> {
return this.verifyToken(token);
}
private async verifyToken(token: string): Promise<AuthenticatedUser | null> {
try {
const payload = verify(token, process.env.JWT_SECRET!) as {
sub: string;
name: string;
};
return {
userId: payload.sub,
displayName: payload.name,
};
} catch {
return null;
}
}
}Where It's Used
| Context | Method Called | Token Source |
|---|---|---|
| REST API controllers | validateRequest() | Authorization: Bearer <token> header |
| WebSocket gateway (join) | validateConnection() | token field in JoinMessage |
When authentication fails:
- REST: The controller returns a 401 or 403 response
- WebSocket: The gateway emits an error message (
AUTH_FAILED) and disconnects the client
Testing
Use MockAuthGuard from the testing utilities for unit tests:
import { MockAuthGuard } from '@hfu.digital/boardkit-nestjs';
const authGuard = new MockAuthGuard();
// All tokens are accepted, returning a test userSee Testing for more details.