Exercise 4: Resource-based Authorization
Objective
Implement authorization where users can only modify their own resources
Scenario
Blog post system where:
- Anyone can read posts
- Authors can update their own posts
- Authors can delete their own posts
- Admins can do anything
Implementation
1. Create Operations
public static class Operations
{
public static OperationAuthorizationRequirement Create = new() { Name = "Create" };
public static OperationAuthorizationRequirement Read = new() { Name = "Read" };
public static OperationAuthorizationRequirement Update = new() { Name = "Update" };
public static OperationAuthorizationRequirement Delete = new() { Name = "Delete" };
}
2. Create Handler
public class PostAuthorizationHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Post>
{
protected override Task HandleRequirementAsync(...)
{
// Implement authorization logic
}
}
3. Use in Endpoint
app.MapPut("/api/posts/{id}", async (int id, IAuthorizationService authService) =>
{
var post = await GetPost(id);
var authResult = await authService.AuthorizeAsync(User, post, Operations.Update);
if (!authResult.Succeeded)
return Results.Forbid();
// Update post
});
Expected Outcome
- Resource ownership validation
- Operation-based authorization
- Fine-grained access control