OwnershipGuard 0.3.0

dotnet add package OwnershipGuard --version 0.3.0
                    
NuGet\Install-Package OwnershipGuard -Version 0.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OwnershipGuard" Version="0.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OwnershipGuard" Version="0.3.0" />
                    
Directory.Packages.props
<PackageReference Include="OwnershipGuard" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OwnershipGuard --version 0.3.0
                    
#r "nuget: OwnershipGuard, 0.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OwnershipGuard@0.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OwnershipGuard&version=0.3.0
                    
Install as a Cake Addin
#tool nuget:?package=OwnershipGuard&version=0.3.0
                    
Install as a Cake Tool

OwnershipGuard

NuGet

OwnershipGuard is an ASP.NET Core library that enforces ownership checks and optional tenant checks before endpoint or MVC action execution. It centralizes resource access validation by route id and helps prevent IDOR and broken access control caused by missing per-endpoint checks.

Requirements

  • .NET 8
  • ASP.NET Core 8

Installation

dotnet add package OwnershipGuard
<PackageReference Include="OwnershipGuard" Version="x.y.z" />

Quick Start

  1. Register services.
using System.Security.Claims;

builder.Services.AddOwnershipGuard(options =>
{
    options.UserIdClaimType = ClaimTypes.NameIdentifier;
    options.TenantIdClaimType = "tenant_id";
    options.UseProblemDetailsResponses = true;
    options.HideExistenceWhenForbidden = false;
    // Optional AccessProof feature:
    // options.AccessProof.Enabled = true;
});
  1. Register descriptors after builder.Build().
var app = builder.Build();
var registry = app.Services.GetRequiredService<IOwnershipDescriptorRegistry>();

// String key + ownership check
registry.Register<Note>(
    sp => sp.GetRequiredService<YourDbContext>().Notes,
    n => n.Id,
    n => n.OwnerId);

// Typed key (Guid) + ownership + tenant check
registry.Register<Document, Guid>(
    sp => sp.GetRequiredService<YourDbContext>().Documents,
    d => d.Id,
    d => d.OwnerId,
    tenantSelector: d => d.TenantId);
  1. Apply the check to endpoints.

Minimal API:

app.MapGet("/documents/{id}", ...).RequireOwnership<Document>("id");
app.MapPut("/documents/{id}", ...).RequireOwnership<Document>("id");

MVC:

[ApiController]
[Route("documents")]
[RequireOwnership("id", typeof(Document))]
public sealed class DocumentsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(string id) => Ok();
}

AccessProof (Optional)

AccessProof issues a short-lived signed token after successful ownership checks. On the next matching request, filter can validate this token and skip DB ownership lookup.

builder.Services.AddDistributedMemoryCache(); // or a real distributed cache provider

builder.Services.AddOwnershipGuard(options =>
{
    options.AccessProof.Enabled = true;
    options.AccessProof.EmitResponseHeader = false;
});

Forwarding to trusted downstream services:

builder.Services
    .AddHttpClient("downstream")
    .AddOwnershipProofForwarding();

Defaults:

  • Enabled = false
  • HeaderName = "X-Ownership-Proof"
  • TokenTtl = 2 minutes
  • EmitResponseHeader = false
  • Invalid/missing proof falls back to normal ownership DB check

Fail-fast:

  • If AccessProof.Enabled = true and IDistributedCache is not registered, startup throws an InvalidOperationException.

Response Behavior

Status Condition
400 Bad Request Route id is missing or empty, or typed key parsing fails (for Register<T, TKey>).
401 Unauthorized User claim is missing, or tenant claim is missing when a tenant-aware descriptor is used.
403 Forbidden Resource exists but ownership or tenant check fails, and HideExistenceWhenForbidden is false.
404 Not Found Resource does not exist, or ownership/tenant check fails when HideExistenceWhenForbidden is true.
500 Internal Server Error Descriptor is not registered for the requested entity type.

Startup Validation (Fail-Fast)

OwnershipGuard validates ownership descriptors during startup.

  • Minimal API endpoints are validated when configured with .RequireOwnership<TEntity>("id").
  • MVC actions are validated when decorated with [RequireOwnership(...)].
  • If a required descriptor is missing, app startup fails with InvalidOperationException and endpoint details.

Plugin Model

OwnershipGuard plugins let you package descriptor registration in reusable modules. Plugins run during app startup before fail-fast descriptor validation.

public sealed class DocumentsOwnershipPlugin : IOwnershipGuardPlugin
{
    public Task ConfigureAsync(OwnershipGuardPluginContext context, CancellationToken cancellationToken = default)
    {
        context.DescriptorRegistry.Register<Document, Guid>(
            sp => sp.GetRequiredService<AppDbContext>().Documents,
            d => d.Id,
            d => d.OwnerId,
            tenantSelector: d => d.TenantId);

        return Task.CompletedTask;
    }
}

builder.Services
    .AddOwnershipGuard()
    .AddOwnershipGuardPlugin<DocumentsOwnershipPlugin>();

Analyzer Rules & Migration

OwnershipGuard ships with built-in Roslyn guardrails to enforce canonical wiring patterns in IDE and CI.

  • OG1001 (Error): flags raw Minimal API ownership wiring through .AddEndpointFilter(...) when RequireOwnershipFilter is used.
    • Preferred form: .RequireOwnership<TEntity>("id")
  • OG1002 (Error): flags raw MVC ownership wiring through [TypeFilter(...)] / [ServiceFilter(...)] with RequireOwnershipActionFilter.
    • Preferred form: [RequireOwnership("id", typeof(TEntity))]

You can suppress rules per standard Roslyn flow (.editorconfig, NoWarn) when needed.

Minimal API migration example:

// before
app.MapGet("/documents/{id}", ...).AddEndpointFilter(new RequireOwnershipFilter("id", typeof(Document)));

// after
app.MapGet("/documents/{id}", ...).RequireOwnership<Document>("id");

MVC migration example:

// before
[TypeFilter(typeof(RequireOwnershipActionFilter), Arguments = new object[] { "id", typeof(Document) })]

// after
[RequireOwnership("id", typeof(Document))]

Configuration

Option Default Description
UserIdClaimType ClaimTypes.NameIdentifier Claim type used to resolve the current user id.
TenantIdClaimType "tenant_id" Claim type used to resolve the current tenant id when tenant checks are required.
UseProblemDetailsResponses true When true, filters return ProblemDetails payloads for errors. When false, filters return plain status responses.
HideExistenceWhenForbidden false When true, failed ownership/tenant checks return 404; otherwise they return 403.
AccessProof.Enabled false Enables signed ownership proof issue/validation flow.
AccessProof.HeaderName "X-Ownership-Proof" Header used to receive/emit proof token.
AccessProof.TokenTtl 00:02:00 Proof token lifetime.
AccessProof.MaxHeaderLength 4096 Maximum accepted proof token length.
AccessProof.Issuer "OwnershipGuard" Issuer claim validated during proof checks.
AccessProof.Audience "internal" Audience claim validated during proof checks.
AccessProof.EmitResponseHeader false Emits fresh proof token in response header when ownership check succeeds.

Optional error message overrides (when set, used as ProblemDetails.Title; when null, built-in defaults are used): MissingResourceIdMessage, InvalidResourceIdInRouteMessage, UnauthorizedMessage, TenantNotSpecifiedMessage, InvalidResourceIdMessage, NotFoundMessage, ForbiddenMessage, DescriptorNotRegisteredMessage. Useful for i18n or custom wording.

Optional Query Helpers

using OwnershipGuard.EntityFrameworkCore;

var ownedDocs = await db.Documents
    .WhereOwnedBy(userId, d => d.OwnerId)
    .ToListAsync();

var tenantDocs = await db.Documents
    .WhereTenant(tenantId, d => d.TenantId)
    .ToListAsync();

Non-Goals

OwnershipGuard does not implement:

  • Authentication
  • Authorization policy systems (RBAC)
  • Rate limiting
  • Input validation

License

MIT. See LICENSE.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.0 92 2/19/2026
0.2.0 95 2/12/2026
0.1.0 95 2/11/2026

Built-in Roslyn analyzer guardrails (OG1001/OG1002) with code fixes for canonical OwnershipGuard wiring, plus startup fail-fast validation and coverage-enforced test suite.