Overview
The@CrudAuth() decorator provides built-in authentication and authorization for CRUD operations. It allows you to filter queries, persist user data, and control access based on the authenticated user.
Basic Usage
Apply the@CrudAuth() decorator to your controller:
me.controller.ts
Configuration Options
The@CrudAuth() decorator accepts an AuthOptions object:
Filter
Automatically filter queries based on the authenticated user:getMany, getOne).
Persist
Automatically add user data to create/update operations:my-projects.controller.ts
persist function automatically adds userId to all create and update requests.
OR Conditions
Add OR conditions to your filters:Class Transform Options
Customize serialization based on the user:Groups
Shorthand for setting serialization groups:Global Configuration
Set global authentication settings inmain.ts:
main.ts
The
property option specifies where to find the authenticated user on the request object (e.g., req.user).Complete Example
Here’s a comprehensive authentication setup:projects.controller.ts
Using with Guards
Combine with NestJS guards for authentication:auth.guard.ts
app.module.ts
Multi-Tenancy Example
Implement multi-tenancy with company-based filtering:users.controller.ts
Advanced Filtering
Use complex conditions in your filters:Request Property
Access the user from different request properties:Security Best Practices
1
Always Use Guards
Combine
@CrudAuth() with authentication guards to ensure only authenticated users can access endpoints.2
Filter Sensitive Data
Use the
filter option to ensure users can only access their own data or data they’re authorized to see.3
Validate Ownership
For update and delete operations, ensure users can only modify resources they own.
4
Use Serialization
Combine with serialization to control which fields different user roles can see.
Troubleshooting
User Not Found on Request
If the user object is not found:- Ensure your authentication guard sets
request.user - Verify the
propertyconfiguration matches your setup - Check that the guard executes before CRUD operations
Filters Not Applied
If filters aren’t working:- Verify the filter function returns a valid condition object
- Check that field names match your entity properties
- Ensure the user object has the expected properties
Related Resources
- Global Configuration - Set global auth settings
- Serialization - Control response data based on user role
- Query Options - Learn about query filtering