Preventing IDOR and Broken Access Control in ASP.NET Core

A comprehensive security engineering guide to preventing IDOR and broken access control in ASP.NET Core using resource-based authorization, EF Core query filters, and GUIDs.

Abstract cybersecurity composition: IDOR & Broken Access Control defense architecture in ASP.NET Core with red security accents

Insecure Direct Object References (IDOR), classified under Broken Access Control (A01:2021 in the OWASP Top 10), represent the most common and damaging vulnerability category in modern web APIs. An IDOR occurs when an application exposes a reference to an internal database object—such as an integer primary key, GUID, or file path—in a request URI or payload, and subsequently retrieves or mutates that object without validating that the authenticated user possesses authorization to access that specific resource.

In ASP.NET Core, developers often mistakenly assume that applying the [Authorize] attribute to a controller or action method provides comprehensive security. While [Authorize] establishes authentication (verifying who the caller is) and role-based access control (verifying the caller is a "User" or "Manager"), it completely fails to prevent IDOR because it performs no checks on resource ownership.

Before diving into C# code, ensure your baseline authentication patterns are hardened by reviewing our guides on JWT security best practices and token validation and preventing CORS misconfigurations in web APIs.

The Anatomy of an IDOR Flaw in ASP.NET Core

Consider a typical e-commerce or billing controller written in ASP.NET Core with Entity Framework Core:

// VULNERABLE CONTROLLER ACTION
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class InvoicesController : ControllerBase
{
    private readonly ApplicationDbContext _db;

    public InvoicesController(ApplicationDbContext db) => _db = db;

    [HttpGet("{id:int}")]
    public async Task<IActionResult> GetInvoice(int id)
    {
        // VULNERABILITY: An authenticated user can supply ANY valid invoice ID
        // e.g., Alice (User 101) requests /api/invoices/500 belonging to Bob (User 202).
        var invoice = await _db.Invoices
            .Include(i => i.LineItems)
            .FirstOrDefaultAsync(i => i.Id == id);

        if (invoice == null)
            return NotFound();

        return Ok(invoice);
    }
}

In this implementation, the [Authorize] attribute ensures that anonymous users are rejected with 401 Unauthorized. However, if Alice logs in legitimately and intercepts her request, changing /api/invoices/101 to /api/invoices/102, ASP.NET Core will execute the database query, find Bob's invoice, and serialize his private billing information straight to Alice's browser.

Vulnerability Dimension Inadequate Defense Pattern Production Hardened Defense
Identity Verification Relying solely on [Authorize] Verifying User.FindFirst(ClaimTypes.NameIdentifier) on every request
Data Retrieval _db.Invoices.FindAsync(id) Scoped lookup: _db.Invoices.Where(i => i.UserId == currentUserId)
Complex Logic Hardcoded if (invoice.UserId != user) in actions Decoupled IAuthorizationService with custom AuthorizationHandler
Multi-Tenancy Manual tenant ID checks in every query Automatic EF Core Global Query Filters (HasQueryFilter)
Key Enumeration Sequential auto-increment integer IDs (/invoices/1) Random UUIDv4 / Sqids / Cryptographic obfuscated public identifiers

Technical Control 1: Scoped Queries at the Repository Layer

The simplest and most direct mitigation for straightforward data models is enforcing scoped queries. Instead of querying the database globally by primary key, always constrain the query by the authenticated user's ID extracted from claims:

[Authorize]
[HttpGet("{id:int}")]
public async Task<IActionResult> GetInvoice(int id)
{
    // Extract authenticated user ID from ClaimsPrincipal
    var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
    if (!int.TryParse(userIdClaim, out var currentUserId))
        return Unauthorized();

    // Query is strictly constrained to resources owned by currentUserId
    var invoice = await _db.Invoices
        .Include(i => i.LineItems)
        .FirstOrDefaultAsync(i => i.Id == id && i.UserId == currentUserId);

    if (invoice == null)
    {
        // Security Tip: Return NotFound rather than Forbidden to prevent ID enumeration
        return NotFound();
    }

    return Ok(invoice);
}

By returning 404 Not Found when a record belongs to another user rather than 403 Forbidden, you prevent attackers from discovering whether an invoice ID exists in your system (stopping automated blind enumeration).


Technical Control 2: Resource-Based Authorization with IAuthorizationService

In enterprise applications, ownership is rarely simple. An invoice might be editable by the creator, readable by members of the same organization, and approvable only by an assigned financial manager. Writing nested if statements inside controller actions creates fragile code that leads to access control bypasses.

ASP.NET Core provides a native, decoupled mechanism for this: Resource-Based Authorization.

Step 1: Define an Authorization Requirement and Operation

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;

public static class InvoiceOperations
{
    public static OperationAuthorizationRequirement Read = new() { Name = nameof(Read) };
    public static OperationAuthorizationRequirement Update = new() { Name = nameof(Update) };
    public static OperationAuthorizationRequirement Delete = new() { Name = nameof(Delete) };
}

Step 2: Implement the AuthorizationHandler

Create a handler that evaluates permissions against the actual Invoice instance:

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;

public class InvoiceAuthorizationHandler 
    : AuthorizationHandler<OperationAuthorizationRequirement, Invoice>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        OperationAuthorizationRequirement requirement,
        Invoice resource)
    {
        var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (userId == null)
            return Task.CompletedTask;

        // Admins can perform any operation
        if (context.User.IsInRole("Admin"))
        {
            context.Succeed(requirement);
            return Task.CompletedTask;
        }

        // Owners can read and update their own invoices
        if (resource.UserId.ToString() == userId)
        {
            if (requirement.Name == nameof(InvoiceOperations.Read) ||
                requirement.Name == nameof(InvoiceOperations.Update))
            {
                context.Succeed(requirement);
            }
        }

        return Task.CompletedTask;
    }
}

Step 3: Register the Handler in Program.cs

builder.Services.AddScoped<IAuthorizationHandler, InvoiceAuthorizationHandler>();

Step 4: Enforce the Check in Controller Actions

[Authorize]
[HttpPut("{id:int}")]
public async Task<IActionResult> UpdateInvoice(int id, [FromBody] UpdateInvoiceDto dto)
{
    var invoice = await _db.Invoices.FindAsync(id);
    if (invoice == null)
        return NotFound();

    // Challenge the resource against the registered AuthorizationHandler
    var authorizationResult = await _authorizationService
        .AuthorizeAsync(User, invoice, InvoiceOperations.Update);

    if (!authorizationResult.Succeeded)
    {
        // Enforce strict denial if the user does not own the invoice
        return Forbid();
    }

    invoice.Description = dto.Description;
    invoice.Amount = dto.Amount;
    await _db.SaveChangesAsync();

    return NoContent();
}

Technical Control 3: Global Multi-Tenant Query Filters in EF Core

In software-as-a-service (SaaS) and multi-tenant architectures, developers should not rely on individual developers remembering to add WHERE TenantId = ... in every query. Forgetting this check once creates a catastrophic tenant-isolation IDOR.

Entity Framework Core enables automatic query filtering across all queries via HasQueryFilter.

Step 1: Define an ITenantEntity Interface and Tenant Service

public interface ITenantEntity
{
    int TenantId { get; set; }
}

public interface ITenantProvider
{
    int GetCurrentTenantId();
}

Step 2: Apply the Query Filter in DbContext

public class ApplicationDbContext : DbContext
{
    private readonly ITenantProvider _tenantProvider;

    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options, 
        ITenantProvider tenantProvider) : base(options)
    {
        _tenantProvider = tenantProvider;
    }

    public DbSet<Invoice> Invoices => Set<Invoice>();
    public DbSet<Customer> Customers => Set<Customer>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Automatically filter every query for entities implementing ITenantEntity
        modelBuilder.Entity<Invoice>()
            .HasQueryFilter(i => i.TenantId == _tenantProvider.GetCurrentTenantId());

        modelBuilder.Entity<Customer>()
            .HasQueryFilter(c => c.TenantId == _tenantProvider.GetCurrentTenantId());
    }
}

Whenever any controller or background service calls _db.Invoices.ToListAsync(), EF Core rewrites the generated SQL:

SELECT i.Id, i.Amount, i.TenantId 
FROM Invoices AS i
WHERE i.TenantId = @__ef_filter__TenantId_0

This architectural safeguard prevents cross-tenant data leakage by default.


Technical Control 4: Replacing Sequential IDs with GUIDs or Sqids

Sequential database IDs (1, 2, 3...) tell attackers how many records your database contains and make automated scraping effortless with simple integer increments (curl https://api.site.com/invoices/{1..10000}).

  1. Use UUIDv7 / GUIDs: Expose Guid PublicId in your API contracts while maintaining high-performance sequential clustered indexes internally in SQL Server or PostgreSQL.
  2. Use Sqids (Hashids successor): Encode numeric primary keys into opaque, URL-safe alphanumeric strings:
    var sqids = new SqidsEncoder<int>(new() { MinLength = 10 });
    string publicId = sqids.Encode(invoice.Id); // "7b8KxY1zqW"
    

Automated Security Testing: Verifying IDOR Resistance in xUnit

Never consider authorization complete without automated integration tests asserting that unauthorized users are rejected. Using WebApplicationFactory<Program>, test cross-user access:

public class InvoiceAccessControlTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public InvoiceAccessControlTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task GetInvoice_WhenOwnedByAnotherUser_ReturnsNotFound()
    {
        // Arrange: Generate authentic client authenticated as User 101
        var client = _factory.CreateAuthenticatedClient(userId: 101);

        // Act: Attempt to access Invoice 500 created by User 202
        var response = await client.GetAsync("/api/invoices/500");

        // Assert: The endpoint must refuse access and return 404 (or 403)
        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
    }
}

Security Checklist for Code Reviews

Before deploying ASP.NET Core endpoints to production, verify each action against this checklist:

  • Does the action method retrieve records based on a route parameter ({id})?
  • Is there an explicit ownership check matching User.FindFirst(ClaimTypes.NameIdentifier) or IAuthorizationService.AuthorizeAsync?
  • If the application is multi-tenant, is HasQueryFilter configured in the DbContext?
  • Are internal auto-incrementing integer IDs hidden from public API URLs?
  • Does querying a non-existent or un-owned record return 404 Not Found rather than 403 Forbidden to prevent object enumeration?

Official References and Further Reading


Application Security Defense Matrix: Insecure Direct Object References (IDOR), ASP.NET Core Guide.

Keep reading