Authorization
OtterApi uses the standard ASP.NET Core IAuthorizationService. All policies are
configured through the normal AddAuthorization pipeline and then referenced
by name on the entity builder.
Configuring policies
Program.cs — policy definitions
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("IsAdmin", p => p.RequireRole("Admin"));
options.AddPolicy("IsManager", p => p.RequireRole("Admin", "Manager"));
});
Authorization methods
| Method | Description |
|---|---|
.Authorize() | Requires authentication for all HTTP methods |
.WithEntityPolicy("IsAdmin") | Applies a named policy to all methods (GET / POST / PUT / PATCH / DELETE) |
.WithGetPolicy("IsManager") | Policy for GET only |
.WithPostPolicy("IsAdmin") | Policy for POST only |
.WithPutPolicy("IsAdmin") | Policy for PUT only |
.WithPatchPolicy("IsAdmin") | Policy for PATCH only |
.WithDeletePolicy("IsAdmin") | Policy for DELETE only |
Combining policies
EntityPolicy is checked first, then the method-specific policy.
Both must pass for the request to proceed.
Layered authorization
options.Entity<Product>("products")
.Authorize() // any authenticated user can read
.WithPostPolicy("IsManager") // POST requires Manager role
.WithPutPolicy("IsManager") // PUT requires Manager role
.WithPatchPolicy("IsManager") // PATCH requires Manager role
.WithDeletePolicy("IsAdmin"); // DELETE requires Admin role
Entity policy + method policy
options.Entity<Report>("reports")
.Authorize()
.WithEntityPolicy("IsManager") // all methods need Manager role
.WithDeletePolicy("IsAdmin"); // DELETE also needs Admin role
Authorization error codes
| Status | Meaning |
|---|---|
401 Unauthorized | User is not authenticated (no valid token) |
403 Forbidden | User is authenticated but does not have the required policy / role |
Authorization is only enforced if
UseOtterApi() is placed after
UseAuthentication() and UseAuthorization() in the middleware pipeline.
See Configuration for the correct order.