Security Decorators
Define TypeScript authentication, roles, permissions, policies, rate limits, CSRF, sanitization, IP allow lists and verified email with AxilJS.
On this page17
AxilJS security decorators declare access-control and security requirements as semantic metadata.
Instead of implementing authorization logic directly inside application methods, you describe the security requirement and let the appropriate security consumer enforce it.
Security decorators cover:
- Authentication
- Roles and permissions
- Authorization policies
- Rate limiting
- CSRF protection
- Input sanitization
- IP allowlists
- Verified identities
@tAuth
tAuth declares that an operation requires an authenticated caller.
1import { tAuth } from '@axiljs/decorator'
2
3@tAuth()
4async getProfile() {}Authentication requirements can be configured for specific authentication schemes or stronger authentication requirements:
1@tAuth({
2 required: true,
3 schemes: ['bearer', 'apiKey'],
4 mfa: true
5})
6async transferFunds() {}Options
| Option | Type | Description |
|---|---|---|
required | boolean | Whether authentication is required |
schemes | string[] | Accepted authentication schemes |
mfa | boolean | Require multi-factor authentication |
By default, required is true.
@tRole
tRole restricts an operation to callers with the specified role.
@tRole('admin')
async deleteUser() {}Multiple roles can be declared:
@tRole('admin', 'editor')
async publishPost() {}Use roles for coarse-grained access control.
For resource-level or relationship-based authorization, use @tPolicy.
@tPermission
tPermission defines fine-grained permissions required to execute an operation.
@tPermission('users.write')
async createUser() {}Multiple permissions can be required (the caller must hold all of them):
1@tPermission(
2 'orders.read',
3 'orders.update'
4)
5async updateOrder() {}Permissions are useful when role-based access control is too broad for the application's authorization model.
@tPolicy
tPolicy references a named authorization policy.
Use policies when authorization depends on application context rather than a simple role or permission.
@tPolicy('OrderOwnership')
async updateOrder(orderId: string) {}Another example:
@tPolicy('TenantAdmin')
async manageSettings() {}The policy consumer evaluates the named policy against the current execution context.
Typical policy inputs may include:
- Current user
- Resource being accessed
- Tenant
- User roles
- User permissions
- Resource ownership
- Organization membership
The policy determines whether the operation is allowed.
@tRateLimit
tRateLimit constrains how frequently an operation can execute.
1@tRateLimit({
2 limit: 10,
3 window: '1m'
4})
5async search() {}The rate limit can be scoped to a specific identity or request attribute:
1@tRateLimit({
2 limit: 5,
3 window: '15m',
4 key: 'ip'
5})
6async login() {}Options
| Option | Type | Description |
|---|---|---|
limit | number | Maximum number of executions |
window | string | Time window such as 10s, 1m, or 1h |
key | string | Rate-limit grouping key such as ip, user, or tenant |
Rate limiting can be particularly useful for:
- Authentication endpoints
- Public APIs
- Search endpoints
- Expensive operations
- Tenant-specific API limits
@tCsrf
tCsrf declares that an operation requires a valid Cross-Site Request Forgery (CSRF) token.
@tCsrf()
async updateSettings() {}Use this for state-changing operations where CSRF protection is required.
The security consumer is responsible for validating the token according to the application's configured CSRF mechanism.
@tSanitize
tSanitize declares input sanitization requirements.
1@tSanitize({
2 stripHtml: true,
3 trim: true
4})
5async createComment(
6 @tBody() dto: CommentDto
7) {}Options
| Option | Type | Description |
|---|---|---|
stripHtml | boolean | Remove HTML markup |
trim | boolean | Trim leading and trailing whitespace |
normalizeWhitespace | boolean | Collapse repeated whitespace |
Sanitization should complement validation rather than replace it.
For schema validation, use the validation decorators.
@tIpAllowList
tIpAllowList restricts access to configured IP addresses or CIDR ranges.
1@tIpAllowList(
2 '192.168.1.0/24',
3 '10.0.0.1'
4)
5async internalEndpoint() {}This is useful for endpoints intended for:
- Internal services
- Private infrastructure
- Administrative operations
- Trusted network environments
IP-based restrictions should generally be treated as an additional security boundary, not the sole authorization mechanism.
@tVerifiedEmail
tVerifiedEmail requires the authenticated user's email address to be verified.
@tVerifiedEmail()
async createOrder() {}This is useful when an operation requires a verified account identity.
Composing Security Requirements
Security decorators are designed to be composed.
For example:
1@tHttp({
2 method: 'DELETE',
3 path: '/users/:id'
4})
5@tAuth({ required: true })
6@tRole('admin')
7@tRateLimit({
8 limit: 5,
9 window: '1h'
10})
11@tIpAllowList('10.0.0.0/8')
12@tAudit({
13 action: 'user.deleted',
14 sensitivity: 'high'
15})
16async deleteUser(
17 @tParam('id') id: string
18) {
19 await this.userService.delete(id)
20}Each declaration represents a separate security or operational requirement:
| Decorator | Responsibility |
|---|---|
tAuth | Authentication |
tRole | Role-based authorization |
tRateLimit | Request frequency control |
tIpAllowList | Network restriction |
tAudit | Security and compliance auditing |
The decorators remain independent. The security runtime can evaluate the relevant metadata without requiring the decorators themselves to know how authentication, authorization, or rate limiting is implemented.
Security Metadata
Security decorators write their declarations to the AxilJS metadata registry.
A security consumer can then inspect the metadata and enforce the required constraints:
This separates the declaration of a security requirement from its implementation.
Complete Example
A protected API operation can combine HTTP, authentication, authorization, rate limiting, and auditing:
1import {
2 tHttp,
3 tAuth,
4 tPermission,
5 tRateLimit,
6 tAudit,
7 tParam
8} from '@axiljs/decorator'
9
10@tHttp({
11 method: 'DELETE',
12 path: '/orders/:id'
13})
14@tAuth()
15@tPermission('orders.delete')
16@tRateLimit({
17 limit: 10,
18 window: '1m',
19 key: 'user'
20})
21@tAudit({
22 action: 'order.deleted'
23})
24async deleteOrder(
25 @tParam('id') orderId: string
26) {
27 return this.orderService.delete(orderId)
28}The business method remains focused on the operation itself while its security requirements remain explicit and machine-readable.
Security Decorator Reference
| Decorator | Purpose |
|---|---|
tAuth | Require authentication |
tRole | Require one or more roles |
tPermission | Require specific permissions |
tPolicy | Apply a named authorization policy |
tRateLimit | Limit execution frequency |
tCsrf | Require CSRF protection |
tSanitize | Declare input sanitization |
tIpAllowList | Restrict access by IP or CIDR |
tVerifiedEmail | Require a verified email identity |
Security and Other Decorators
Security decorators can be combined with decorators from other AxilJS domains.
For example:
HTTP
+
Authentication
+
Authorization
+
Rate Limiting
+
Transaction
+
Audit
+
ObservabilityThis allows the complete operational contract of an endpoint to remain visible in its declarations while implementation details remain inside independent runtime consumers.
Was this page helpful?