Lesson 2 of 8
Resource-Based Authorization - Ownership Checks
The [Authorize] attribute runs before model binding - it can't check if the current user OWNS the specific document being accessed. Resource-based authorization checks ownership at action time with the actual resource loaded.
IAuthorizationService with Resource Context
// ━━ Resource-based requirement - 'same user or admin' ━━
public class SameUserOrAdminRequirement : IAuthorizationRequirement { }
public class SameUserOrAdminHandler
: AuthorizationHandler<SameUserOrAdminRequirement, IOwnedResource>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
SameUserOrAdminRequirement requirement,
IOwnedResource resource)
{
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
// Admin can always access
if (context.User.IsInRole("Admin"))
{
context.Succeed(requirement);
return Task.CompletedTask;
}
// User can only access their own resources
if (userId is not null && resource.OwnerId == userId)
context.Succeed(requirement);
else
context.Fail(new AuthorizationFailureReason(this, "You don't own this resource"));
return Task.CompletedTask;
}
}
public interface IOwnedResource { string OwnerId { get; } }
// ━━ Usage in controller - load resource, then authorize ━━
[ApiController, Route("api/documents")]
public class DocumentsController(
IDocumentRepository docs,
IAuthorizationService authorizationService) : ControllerBase
{
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
// 1. Load the resource
var document = await docs.FindByIdAsync(id, ct);
if (document is null) return NotFound();
// 2. Check ownership AFTER loading
var authResult = await authorizationService.AuthorizeAsync(
User,
document, // the actual resource (implements IOwnedResource)
"SameUserOrAdmin"); // policy name
if (!authResult.Succeeded)
return Forbid(); // 403 - authenticated but not authorized
// 3. Perform action
await docs.DeleteAsync(id, ct);
return NoContent();
}
}
// Registration:
builder.Services.AddSingleton<IAuthorizationHandler, SameUserOrAdminHandler>();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("SameUserOrAdmin", policy =>
policy.Requirements.Add(new SameUserOrAdminRequirement()));
interface IDocumentRepository { Task<Document?> FindByIdAsync(Guid id, CancellationToken ct); Task DeleteAsync(Guid id, CancellationToken ct); }
class Document : IOwnedResource { public Guid Id { get; set; } public string OwnerId { get; set; } = ""; public string Title { get; set; } = ""; }Tip
Tip
Practice ResourceBased Authorization Ownership Checks in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of ResourceBased Authorization Ownership Checks from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with ResourceBased Authorization Ownership Checks is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?