| name | servicestack-authorization |
| description | Applies role-, permission-, and ownership-based authorization using ServiceStack idioms. |
ServiceStack Authorization
Authorization in ServiceStack is typically handled via attributes applied to Request DTOs or Service classes.
Roles and Permissions
[RequiredRole("Admin")]: Requires the user to have the "Admin" role.
[RequiresAnyRole("Admin", "Manager")]: Requires any of the specified roles.
[RequiredPermission("CanEdit")]: Requires the user to have a specific permission.
[RequiredRole("Admin")]
public class AdminOnlyRequest : IReturn<AdminResponse> { ... }
Ownership-Based Authorization
Since ServiceStack's philosophy is "it's just code," ownership checks are often implemented inside the service:
public object Any(UpdateOrder request)
{
var order = Db.SingleById<Order>(request.Id);
if (order.CreatedBy != GetSession().UserAuthId)
throw HttpError.Forbidden("You do not own this order.");
}
Custom Authorization Filters
You can create custom attributes by inheriting from AuthenticateAttribute or implementing IHasRequestFilter.
Best Practices
- Apply to DTOs: Prefer applying authorization attributes to Request DTOs in the
ServiceModel project. This ensures visibility in the metadata and Swagger.
- Composition: You can combine multiple roles/permissions on a single DTO.
- ServiceStack Idioms: Avoid manual
if (User.IsInRole(...)) in services whenever possible; use the declarative attributes to keep the service code clean.
- Metadata: Authorization requirements are automatically included in the ServiceStack metadata pages.