resource-authorization
БесплатноБез исполняемых скриптовНе проверенResource-based authorization in ASP.NET Core 10 so users only reach their own data (IDOR): owner-scoped by-id queries, 404 not 403, resource authorization…
от codewithmukesh★ 858 звёзд на GitHubОб этом скилле
Resource Authorization
Core Principles
- Signed in is not the same as allowed to see this row.
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. - Scope in the query, not after the load.
Where(o => o.Id == id && o.OwnerId == user.Id)is one round trip and leaves nothing to forget. A check written afterFindAsyncis a line someone deletes in a refactor. - Another user's resource is a 404, not a 403. A 403 confirms the ID exists, which lets an attacker enumerate IDs. Answer exactly as if the row did not exist. Use 403 only when the caller can see the resource but not change it.
- The owner comes from the token, never from the request. Never trust an
ownerIdin the body, the query string or a route like/users/{userId}/orders. Read it from the authenticated principal. - Prove it with a test. User A creates an order and user B asks for it. Guid IDs are not authorization; they are just harder to guess.
Patterns
ICurrentUser from the token
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.
Owner-scoped reads, updates and deletes
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.
Named query filters for owner and tenant scoping (EF Core 10)
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 `ITen
Установить resource-authorization в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл resource-authorization?
Resource-based authorization in ASP.NET Core 10 so users only reach their own data (IDOR): owner-scoped by-id queries, 404 not 403, resource authorization handlers, EF Core 10 named owner/tenant filters and the cross-user test. Use for "IDOR", "owner check", "users see other users' data", "tenant isolation". Do NOT use for login, JWT or roles (use authentication).
Как установить скилл resource-authorization?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл resource-authorization запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic