Authorization filters complement Nest guards. Use a guard for authentication and coarse endpoint access; use an authorizer for
record-level visibility.
Inline authorizer
Decorate the response DTO with@Authorize. The first argument is the HTTP request and the second describes the generated operation.
todo-item.dto.ts
Authorizer class
Use an injectable class for more involved rules:todo-item.authorizer.ts
todo-item.dto.ts
AuthorizationContext contains:
operationName: generated controller method name, such asqueryManyorupdateOne.operationGroup:read,create,update,delete, orexport.readonly: whether the operation does not modify data.many: whether the operation can affect multiple records.
endpoints or dtos.
Add a guard
Ensure the request has a user before the authorizer runs:read, create, update, delete, and export operation options.
Applying auth filters on creation
The authorizer runs forcreateOne, but by default the filter it returns is not enforced against the request body; the authorizer can only reject a create by throwing, as shown above. Set validateWithAuthFilter in the create options to also enforce the filter:
ownerId different from request.user.id, is rejected with a BadRequestException (HTTP 400) and the message Entity does not meet creation constraints. The option only takes effect when the authorizer resolves a filter for the create operation group; if no authorizer is registered for the DTO, or it returns no filter for create operations, the option is a no-op.