/dotnet-agent-kit:resource-authorizationfrom dotnet Agent Kit
Implements resource-based authorization in ASP.NET Core 10 to prevent IDOR vulnerabilities: owner-scoped queries, 404 instead of 403, resource authorization handlers, and EF Core 10 tenant filters.
Ships in dotnet Agent Kit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
RequireAuthorization() runs before the resource is loaded, so it can only say who the caller is. Every by-id read and write must also prove the row belongs to them. Missing this is OWASP API1 (broken object level authorization), the most common API vulnerability.Where(o => o.Id == id && o.OwnerId == user.Id) is one round trip and leaves nothing to forget. A check written after FindAsync is a line someone deletes in a refactor.ownerId in the body, the query string or a route like /users/{userId}/orders. Read it from the authenticated principal.public interface ICurrentUser
{
string Id { get; }
bool IsInRole(string role);
}
internal sealed class HttpCurrentUser(IHttpContextAccessor accessor) : ICurrentUser
{
// Only resolved behind RequireAuthorization(), so a missing user is a wiring bug, not an expected failure.
public string Id => accessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier)
?? throw new InvalidOperationException("ICurrentUser was used on an endpoint without authentication.");
public bool IsInRole(string role) => accessor.HttpContext?.User.IsInRole(role) ?? false;
}
Register it with builder.Services.AddHttpContextAccessor() and builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>(). JWT bearer maps sub to ClaimTypes.NameIdentifier by default. If you set MapInboundClaims = false, read "sub" instead.
internal sealed class GetMyOrderHandler(OrdersDbContext db, ICurrentUser user) : IHandler
{
public async Task<Results<Ok<OrderSummary>, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
{
var order = await db.Orders.AsNoTracking()
.Where(o => o.Id == id && o.OwnerId == user.Id) // the owner is part of the key
.Select(o => new OrderSummary(o.Id, o.Total))
.FirstOrDefaultAsync(ct);
return order is null ? Problems.NotFound() : TypedResults.Ok(order);
}
}
internal sealed class DeleteMyOrderHandler(OrdersDbContext db, ICurrentUser user) : IHandler
{
public async Task<Results<NoContent, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
{
var deleted = await db.Orders
.Where(o => o.Id == id && o.OwnerId == user.Id)
.ExecuteDeleteAsync(ct);
return deleted == 0 ? Problems.NotFound() : TypedResults.NoContent();
}
}
The same predicate goes on ExecuteUpdateAsync and on list queries. A row that is missing and a row owned by someone else take the same path, so the response can't leak the difference.
When every query on an entity must be scoped, put the scope in the model so a new query can't forget it. Named filters (new in EF Core 10) let one query lift a single filter and keep the rest.
public sealed class Invoice
{
public Guid Id { get; set; }
public string OwnerId { get; set; } = "";
public bool IsDeleted { get; set; }
}
public static class InvoiceFilters
{
public const string Owner = "owner";
public const string SoftDelete = "soft-delete";
}
internal sealed class BillingDbContext(DbContextOptions<BillingDbContext> options, ICurrentUser user) : DbContext(options)
{
public DbSet<Invoice> Invoices => Set<Invoice>();
// A property on the context: EF Core re-reads it for every context instance.
private string CurrentUserId => user.Id;
protected override void OnModelCreating(ModelBuilder modelBuilder) =>
modelBuilder.Entity<Invoice>()
.HasQueryFilter(InvoiceFilters.Owner, i => i.OwnerId == CurrentUserId)
.HasQueryFilter(InvoiceFilters.SoftDelete, i => !i.IsDeleted);
}
internal sealed class AllInvoicesForSupportHandler(BillingDbContext db) : IHandler
{
// Support staff see every user's invoices but still never see deleted ones.
public Task<List<Invoice>> HandleAsync(CancellationToken ct) =>
db.Invoices.IgnoreQueryFilters([InvoiceFilters.Owner]).AsNoTracking().ToListAsync(ct);
}
Gate the bypass endpoint with its own permission. Add an architecture test that only lists the filters a query is allowed to lift. In the kit's modular slices, ModuleDbContext already applies the tenant filter to every ITenantOwned entity the same way (modular-slices/references/building-blocks.md).
Ownership fits in a Where. Rules like "owner or anyone it's shared with can read, only the owner can edit" belong in an AuthorizationHandler<TRequirement, TResource>, which runs after the resource is loaded.
public sealed class Document
{
public Guid Id { get; set; }
public string OwnerId { get; set; } = "";
public string Title { get; set; } = "";
public List<string> SharedWith { get; } = [];
}
public static class DocumentOperations
{
public static readonly OperationAuthorizationRequirement Read = new() { Name = nameof(Read) };
public static readonly OperationAuthorizationRequirement Edit = new() { Name = nameof(Edit) };
}
internal sealed class DocumentAuthorizationHandler
: AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, OperationAuthorizationRequirement requirement, Document resource)
{
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var allowed = userId is not null && requirement.Name switch
{
nameof(DocumentOperations.Read) => resource.OwnerId == userId || resource.SharedWith.Contains(userId),
nameof(DocumentOperations.Edit) => resource.OwnerId == userId,
_ => false,
};
if (allowed)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
internal sealed class RenameDocumentHandler(DocsDbContext db, IAuthorizationService authorization) : IHandler
{
public async Task<Results<NoContent, ProblemHttpResult>> HandleAsync(
Guid id, string title, ClaimsPrincipal principal, CancellationToken ct)
{
var document = await db.Documents.FindAsync([id], ct);
if (document is null || !(await authorization.AuthorizeAsync(principal, document, DocumentOperations.Read)).Succeeded)
return Problems.NotFound(); // can't see it: it doesn't exist for them
if (!(await authorization.AuthorizeAsync(principal, document, DocumentOperations.Edit)).Succeeded)
return Problems.Forbidden(); // can see it, can't change it
document.Title = title;
await db.SaveChangesAsync(ct);
return TypedResults.NoContent();
}
}
internal sealed class DocsDbContext(DbContextOptions<DocsDbContext> options) : DbContext(options)
{
public DbSet<Document> Documents => Set<Document>();
}
Register the handler with builder.Services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>(). The endpoint binds ClaimsPrincipal directly. Minimal APIs inject the current user for that parameter.
Extend the test auth handler so a header picks the user (X-Test-User), then prove both reads and writes are refused. See modular-slices/references/testing.md for the fixture.
public sealed class OrderOwnershipTests(ApiFixture fixture) : IClassFixture<ApiFixture>
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task GetOrder_OrderBelongsToAnotherUser_ReturnsNotFound()
{
using var alice = fixture.ClientAs("alice");
using var bob = fixture.ClientAs("bob");
var order = await OrdersApi.PlaceAsync(alice, fixture.ProductId, Ct);
using var response = await bob.GetAsync($"/api/v1/orders/{order.Id}", Ct);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task DeleteOrder_OrderBelongsToAnotherUser_ReturnsNotFoundAndKeepsOrder()
{
using var alice = fixture.ClientAs("alice");
using var bob = fixture.ClientAs("bob");
var order = await OrdersApi.PlaceAsync(alice, fixture.ProductId, Ct);
using var response = await bob.DeleteAsync($"/api/v1/orders/{order.Id}", Ct);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
using var stillThere = await alice.GetAsync($"/api/v1/orders/{order.Id}", Ct);
Assert.Equal(HttpStatusCode.OK, stillThere.StatusCode);
}
}
// BAD — any signed-in user reads any order by changing the ID in the URL
var order = await db.Orders.FindAsync([id], ct);
return order is null ? Problems.NotFound() : TypedResults.Ok(order);
// GOOD — the owner is part of the lookup
var mine = await db.Orders.Where(o => o.Id == id && o.OwnerId == user.Id).FirstOrDefaultAsync(ct);
// BAD — 403 tells the caller the order exists; IDs become enumerable
var order = await db.Orders.FindAsync([id], ct);
if (order is not null && order.OwnerId != user.Id) return Problems.Forbidden();
// GOOD — someone else's order looks exactly like a missing one
if (order is null || order.OwnerId != user.Id) return Problems.NotFound();
// BAD — the caller picks whose orders to read
endpoints.MapGet("/users/{userId}/orders", (string userId, OrdersDbContext db) =>
db.Orders.Where(o => o.OwnerId == userId).ToListAsync());
// GOOD — the owner comes from the token
endpoints.MapGet("/me/orders", (ICurrentUser user, OrdersDbContext db, CancellationToken ct) =>
db.Orders.Where(o => o.OwnerId == user.Id).ToListAsync(ct)).RequireAuthorization();
// BAD — the model is built once and cached; the first user's ID is baked in for everyone
var ownerId = user.Id;
modelBuilder.Entity<Invoice>().HasQueryFilter(InvoiceFilters.Owner, i => i.OwnerId == ownerId);
// GOOD — a property on the DbContext is evaluated per context instance
modelBuilder.Entity<Invoice>().HasQueryFilter(InvoiceFilters.Owner, i => i.OwnerId == CurrentUserId);
// BAD — also brings back soft-deleted rows and, in a tenant app, other tenants' rows
db.Invoices.IgnoreQueryFilters();
// GOOD — lift only the filter this query is allowed to skip
db.Invoices.IgnoreQueryFilters([InvoiceFilters.Owner]);
| Scenario | Recommendation |
|---|---|
| Single-owner resource (my orders, my invoices) | Owner predicate in every by-id query, or a named owner query filter |
| Every query on an entity must be scoped | EF Core 10 named query filter reading a property on the DbContext |
| Multi-tenant SaaS | Named tenant filter on every tenant-owned entity, plus owner checks inside the tenant |
| Shared or delegated access (share with a user, team members) | AuthorizationHandler<OperationAuthorizationRequirement, TResource> after loading |
| Caller can't see the resource at all | 404 with the same body as a missing row |
| Caller can see it but not change it | 403 |
| Support or admin needs to see all users' data | IgnoreQueryFilters([owner]) behind its own permission, never a bare IgnoreQueryFilters() |
| Updates and deletes | ExecuteUpdateAsync / ExecuteDeleteAsync with the owner predicate; 0 rows means 404 |
| Proving it | Integration test: user A creates, user B reads, updates and deletes it and gets 404 each time |
| Who the caller is, login, roles | Use the authentication skill |
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub codewithmukesh/dotnet-agent-kit --plugin dotnet-agent-kit37 skills in this plugin
/api-hardeningProduction hardening for ASP.NET Core 10 APIs: HSTS, forwarded headers behind a proxy (KnownIPNetworks), strict CORS, body and upload limits, security headers, no detailed errors. Use for "HSTS", "forwarded headers", "behind nginx", "CORS", "request size limit", "security headers", "harden for production". Do NOT use for auth (use authentication) or throttling (use rate-limiting).
/architecture-advisorArchitecture selection for new or restructured .NET solutions: asks about domain, team and compliance, then recommends modular slices (default), vertical slice, Clean Architecture or DDD. Use for "which architecture", "new solution", "restructure", "DDD", "project structure", "tech stack". Do NOT use for adding features to a modular-slices codebase (modular-slices), scaffolding (scaffold), or CLAUDE.md (dotnet-init).
/aspireAspire (17.x, requires .NET 10) orchestration: AppHost, service defaults, resource configuration, service discovery, dashboard. Use for "Aspire", "AppHost", "service defaults", "service discovery", "AddDotnetProject", "AddProject", "WithReference", "aspire run". Do NOT use for Dockerfiles or container images (use docker), CI/CD pipelines (use ci-cd), or OpenTelemetry SDK setup (use opentelemetry).
/authenticationAuthentication and authorization for ASP.NET Core: JWT bearer, OpenID Connect, ASP.NET Identity, policies, role and claim-based authorization, API keys, cookie auth. Use for "JWT", "OIDC", "Identity", "claims", "roles", "RequireAuthorization", "API key". Do NOT use for endpoint design (use minimal-api), security schemes in API docs (use openapi), secrets and options binding (use configuration), or which rows a user may see (use resource-authorization).
/build-fixAutonomous loop that drives a broken .NET build or failing tests to green, with bounded iterations and retry guards (build, parse, fix, rebuild; test-fix variant). Use for "fix the build", "make it compile", "fix failing tests", "keep going until it works", "auto-fix". Do NOT use for cleanup of code that already builds (use de-sloppify), writing new tests (use testing or tdd), or a pre-PR check (use verify).
/cachingCaching for .NET 10: HybridCache (the default), output caching, response caching, distributed cache. Use for "cache", "HybridCache", "Redis", "output cache", "IMemoryCache", "cache invalidation", "stampede protection". Do NOT use for EF Core query tuning or N+1 (use ef-core), retry and timeout policies (use resilience), or Redis as a message broker (use messaging).
Other plugins' skills for the same job