LESSON 12 OF 15

Endpoint Authorization and Resource Ownership

This lesson protects API endpoints with roles, claims, policies and resource ownership. It also covers object-level access control, 401 and 403 responses, and secure error contracts.

45 dk 101

Introduction

After JWT authentication has been configured, an important question remains: which resource may a user access, and for which operation? Protecting an endpoint with only [Authorize] confirms that the caller is authenticated, but it does not automatically verify whether that caller owns a particular record.

This lesson combines endpoint-level authorization with object-level authorization. In the example scenario, users can read and update their own documents, while administrators can access all documents. We will also clarify the difference between authentication and authorization by examining HTTP response codes.

1. Separating authorization layers

An API request is commonly evaluated in the following order:

  1. Authentication: Is a bearer token present? Is its signature valid? Has it expired? Are the issuer and audience correct?
  2. Endpoint authorization: Does the user have the role, claim or policy required to call this endpoint?
  3. Resource authorization: Can the user perform the requested operation on this specific object?

If the first stage fails, the API generally returns 401 Unauthorized. If the token is valid but the user lacks the required permission, the result is normally 403 Forbidden. However, applications may deliberately return 404 Not Found when they must avoid revealing whether a protected resource exists.

2. Data model and policy

Begin with an entity that stores ownership information:

public sealed class Document
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public string OwnerId { get; set; } = string.Empty;
}

The authenticated user identifier and OwnerId must use the same format. With ASP.NET Core Identity, this is commonly the identifier managed by UserManager<ApplicationUser>.

Let us define a policy required to access the API:

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("ApiAccess", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "documents.read");
    });

This policy requires both an authenticated principal and a scope=documents.read claim. A separate policy for write operations provides more precise control:

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("DocumentWrite", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "documents.write");
    });

Apply a policy to a controller or action with [Authorize(Policy = "DocumentWrite")]. In a Minimal API, the equivalent is RequireAuthorization("DocumentWrite").

3. Checking ownership in a controller

Policy authorization is the general entry requirement. To evaluate ownership, load the record and compare it with the authenticated user:

[ApiController]
[Route("api/documents")]
public sealed class DocumentsController(
    AppDbContext db,
    IAuthorizationService authorizationService) : ControllerBase
{
    [HttpGet("{id:int}")]
    [Authorize(Policy = "ApiAccess")]
    public async Task<IActionResult> Get(int id, CancellationToken cancellationToken)
    {
        var document = await db.Documents
            .AsNoTracking()
            .SingleOrDefaultAsync(x => x.Id == id, cancellationToken);

        if (document is null)
            return NotFound();

        var isOwner = document.OwnerId == User.FindFirstValue(ClaimTypes.NameIdentifier);
        var isAdmin = User.IsInRole("Admin");

        if (!isOwner && !isAdmin)
            return NotFound();

        return Ok(new { document.Id, document.Title, document.Content });
    }
}

The [Authorize] policy validates the token and scope. The action then checks whether the record exists and whether the current user is its owner or an administrator. Returning NotFound to an unauthorized caller is a deliberate design that hides the document's existence. It is not mandatory for every application; security, auditing and user-experience requirements should be considered together.

4. Secure update operations

Update operations require additional care. Trusting an OwnerId supplied by the client can create a privilege-escalation vulnerability. Ownership must be derived from the database record and the authenticated identity:

public sealed record UpdateDocumentRequest(string Title, string Content);

[HttpPut("{id:int}")]
[Authorize(Policy = "DocumentWrite")]
public async Task<IActionResult> Update(
    int id,
    UpdateDocumentRequest request,
    CancellationToken cancellationToken)
{
    var document = await db.Documents
        .SingleOrDefaultAsync(x => x.Id == id, cancellationToken);

    if (document is null)
        return NotFound();

    var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
    var canManageAll = User.IsInRole("Admin");

    if (!canManageAll && document.OwnerId != userId)
        return NotFound();

    document.Title = request.Title.Trim();
    document.Content = request.Content;
    await db.SaveChangesAsync(cancellationToken);

    return NoContent();
}

Even if the client sends an OwnerId field, that value should never determine the authorization decision. Otherwise, a user could submit another user's identifier and bypass the ownership rule.

5. IAuthorizationService and resource-based authorization

Instead of duplicating ownership logic in every controller, use IAuthorizationService with a custom handler. Resource-based authorization is appropriate when the decision depends on both user claims and properties of the loaded resource.

public sealed class DocumentOwnerRequirement : IAuthorizationRequirement
{
}

public sealed class DocumentOwnerHandler
    : AuthorizationHandler<DocumentOwnerRequirement, Document>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        DocumentOwnerRequirement requirement,
        Document resource)
    {
        var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
        var isOwner = userId is not null && resource.OwnerId == userId;
        var isAdmin = context.User.IsInRole("Admin");

        if (isOwner || isAdmin)
            context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

Register the handler and policy with dependency injection:

builder.Services.AddSingleton<IAuthorizationHandler, DocumentOwnerHandler>();

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("DocumentOwner", policy =>
        policy.Requirements.Add(new DocumentOwnerRequirement()));

Call authorization after the resource has been loaded:

var authorization = await authorizationService.AuthorizeAsync(
    User,
    document,
    "DocumentOwner");

if (!authorization.Succeeded)
    return NotFound();

The [Authorize] attribute is evaluated before the action executes. At that point, a document parameter may not yet have been loaded from the database. For ownership checks, imperative authorization through AuthorizeAsync is therefore the appropriate pattern.

6. 401, 403 and secure error contracts

StatusMeaningExample
401The request could not be authenticatedBearer token is missing, expired or has an invalid signature
403The identity is authenticated but lacks permissionValid token, but required scope or role is missing
404The resource is absent or its existence is intentionally hiddenAttempt to access another user's document

An API should not expose exception details, database keys or internal authorization decisions to clients. A standard Problem Details contract can be enabled as follows:

builder.Services.AddProblemDetails();

app.UseExceptionHandler();

When a custom response is necessary, keep the response body general:

return Problem(
    statusCode: StatusCodes.Status403Forbidden,
    title: "Access denied",
    detail: "The current user cannot perform this operation.");

In production, do not expose stack traces, SQL statements, user email addresses or internal service names. A stable traceId can be returned to the client while detailed diagnostic information remains in server-side logs.

7. Common mistakes

  • Relying only on roles: The Admin role may grant broad management permissions, but it does not describe ownership of every individual resource.
  • Trusting client ownership data: A request body's OwnerId or UserId must not drive authorization.
  • Confusing decoding with validation: Reading JWT contents does not replace signature, issuer, audience and lifetime validation.
  • Mixing up 401 and 403: An invalid token and insufficient permission are different conditions.
  • Authorizing before loading the resource: A route identifier alone does not reveal who owns the record.
  • Returning overly detailed errors: Messages such as “the resource exists but belongs to another user” can leak information.
  • Using mass assignment: Bind to DTOs containing only fields that the client is allowed to change.

8. Practice exercise

Create a DocumentsController and implement the following rules:

  1. Require the ApiAccess policy for protected endpoints.
  2. Allow a document owner to update only their own record.
  3. Allow users in the Admin role to update any document.
  4. Add an endpoint that returns 403 when the token lacks the required scope.
  5. Return 404 for another user's document so that resource existence is not disclosed.
  6. Test missing token, invalid token, insufficient scope, owner and administrator scenarios through Swagger.

Record the HTTP status code, relevant claims and expected result for each request in a test matrix. This documents authorization rules as an explicit access model rather than leaving them implicit in controller code.

Conclusion

Endpoint protection and resource ownership are not the same concern. Roles, claims and policies define general access rules, while object-level authorization evaluates the relationship between the current user and a specific resource. IAuthorizationService and custom handlers make this logic centralized, reusable and testable.

In the next stage, these rules can be combined with client applications, CORS and API access controls. Before moving on, verify that your application deliberately distinguishes 401, 403 and 404 responses and does not disclose more information than the client needs.

Sources