GateKeeper is HeronJS’s authorization layer. It extracts authentication data from an incoming request, converts that data into a security context, and makes that context available to @Guard() checks.
Register GateKeeper
Use @GateKeeper() on the root module to connect two parts of the authorization flow:
- A
SecureContextclass that maps authentication data into roles and permissions. - An
AuthResolverobject that tells HeronJS how to read and resolve credentials from the incoming request.
@GateKeeper(AuthContext, AuthContextResolver)
export class AppModule {}Create a secure context
The secure context receives resolved authentication data and transforms it into a structure that guards can evaluate.
Example file:
src/context/auth.context.ts
import { SecureContext, SecureProperty } from '@heronjs/common';
import { Observable, of } from 'rxjs';
export class AuthContext implements SecureContext<JWTToken, SecureProperty> {
OnGuard(data: JWTToken): Observable<SecureProperty> {
return of({
roles: data?.roles || ['admin'],
permissions: data?.permissions || ['add-todo'],
});
}
}In this example, the secure context exposes roles and permissions, which can later be checked by @Guard().
Create an auth resolver
AuthResolver tells HeronJS where to read authentication data from for HTTP and WebSocket requests, and how to transform that raw value into a resolved token or auth object.
It commonly includes:
httpto define where the HTTP credential comes from.wsto define where the WebSocket credential comes from.resolve()to parse or verify the extracted value.
| Property | Supported values | Description |
|---|---|---|
http | header, cookie, session | Defines where to read auth data from an HTTP request. |
ws | handshake, header | Defines where to read auth data from a WebSocket connection. |
HeronJS also provides helpers such as JWTResolver for JWT-based authentication flows.
export const AuthContextResolver: AuthResolver<JWTToken> = {
http: ['header', 'authorization'],
ws: ['handshake', 'token'],
resolve: async (data?: string): Promise<Any> => {
return data;
},
};In a real application, resolve() typically verifies the token and returns the decoded auth payload.
Protect routes with guards
Use @Guard() on a controller method to restrict access based on the roles and permissions returned by the secure context.
import { Get, Guard, Rest } from '@heronjs/common';
@Rest('/todos')
export class TodoController {
@Get({ uri: '/' })
@Guard({ roles: ['admin'], permissions: ['add-todo'] })
public async findAll(): Promise<string[]> {
return ['todo1'];
}
}This route is accessible only when the resolved security context contains the required role and permission.