Web & DataComplete guide

Authentication & Authorization

Authentication establishes who a principal is; authorization decides what that principal may do in a specific context.

Overview

ASP.NET Core authentication handlers validate credentials such as cookies or bearer tokens and construct a ClaimsPrincipal. A scheme selects the handler that authenticates, challenges an anonymous caller, or forbids an authenticated caller. APIs should accept OAuth access tokens from a trusted authorization server and validate signature, issuer, audience, lifetime, and algorithms before trusting claims; ID tokens are for clients and are not API access tokens. Authorization then evaluates roles, claims, scopes, named policies, custom requirements, and the actual resource. Declarative policies work for decisions known before a record is loaded, while ownership and tenant decisions require imperative resource authorization. Production design also includes deny-by-default fallback policy, cookie protections, token and key rotation, revocation expectations, multiple schemes, least privilege, 401 versus 403 semantics, deliberate non-disclosure, and negative tests. A valid identity never proves permission to every function or object, and client-side visibility is never a server authorization boundary.

What you will learn

  • Separate authenticate, challenge, forbid, sign-in, sign-out, and authorization responsibilities.
  • Choose cookies, bearer access tokens, or multiple schemes from client and trust-boundary requirements.
  • Validate access tokens and distinguish them from ID tokens, refresh tokens, and application sessions.
  • Model permissions with policies, requirements, handlers, roles, scopes, and claims.
  • Apply resource and tenant authorization after loading the target object.
  • Return deliberate 401, 403, and non-disclosing 404 responses and test negative paths.
  • Operate identity safely through key rotation, token lifetime, telemetry, and incident response.

Prerequisites

  • HTTP status codes, headers, cookies, TLS, and browser versus API behavior.
  • ASP.NET Core dependency injection, middleware, routing, and configuration.
  • Basic familiarity with claims, OAuth 2.0, OpenID Connect, JWT structure, and signatures.
  • A .NET 10 SDK to run the dedicated document-authorization sample.

When to use Authentication & Authorization

Good fit

  • Use secure cookies when a server-rendered browser application owns the session and can enforce antiforgery controls.
  • Use validated OAuth access tokens for APIs called by native, browser, service, or delegated clients.
  • Use named policies for reusable permission rules and resource handlers for ownership, tenant, or state decisions.
  • Use a fallback policy when authenticated access should be the default.

Choose another approach when

  • Do not invent production token formats when a standards-based identity platform is available.
  • Do not use an ID token as authorization to call an API.
  • Do not encode rapidly changing object permissions into long-lived tokens when request-time checks are required.
  • Do not rely on CORS, hidden buttons, gateway-only checks, or possession of any valid token as authorization.

Key concepts

Schemes and handlers

A scheme selects the handler that authenticates, challenges, or forbids a request.

Claims principal

One or more identities and their claims represent the authenticated caller.

Policy authorization

Named policies combine reusable requirements that handlers evaluate against user and resource.

Token lifecycle

Issuance, audience, expiry, rotation, revocation, and key management shape token safety.

OAuth and OpenID Connect

OAuth delegates API access; OpenID Connect adds authentication and ID tokens for the client. Token type and audience must not be confused.

Resource authorization

Ownership, tenant, operation, and resource state are evaluated after loading the target record.

Fallback policy

A fallback policy protects endpoints without explicit authorization metadata; genuinely public endpoints opt out deliberately.

Challenge and forbid

Unauthenticated callers receive 401 and a challenge, while authenticated callers without permission receive 403; selected lookups may return 404 to avoid disclosure.

Architecture

A client obtains credentials from a trusted identity provider. The application validates them, builds a principal, evaluates endpoint policy, loads the target resource, and performs resource authorization before returning minimum permitted data.

User or workload
Identity provider
Authentication handler
Claims principal
Endpoint policy
Resource load
Resource authorization
Protected response

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated sample uses a local-only test scheme so every outcome is runnable without external infrastructure. It requires identity by default, applies a scope policy for creation, and uses an ownership-or-administrator handler for document reads.

  1. 01
    Choose the trust model

    Identify clients, token issuer, audience, credential type, session boundary, and TLS termination.

  2. 02
    Register schemes

    Configure cookie, JWT bearer, certificate, or approved handlers with explicit defaults and strict validation.

  3. 03
    Define policies

    Express business permissions through named policies and requirements instead of scattered strings.

  4. 04
    Protect by default

    Apply fallback or group policy and mark genuinely public endpoints explicitly.

  5. 05
    Authorize resources

    Load within the tenant boundary and authorize the user-resource-operation tuple.

  6. 06
    Map failures

    Return 401 for unacceptable identity, 403 for insufficient permission, and deliberate 404 only to prevent disclosure.

  7. 07
    Test denials

    Cover anonymous, invalid, missing-scope, wrong-role, wrong-tenant, non-owner, owner, and administrator paths.

Code example

A policy expresses business permission as a named requirement instead of scattering claim checks through endpoints.

Authorization.cs
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("CanApproveExpense", policy => policy
        .RequireAuthenticatedUser()
        .RequireClaim("permission", "expense:approve"));

app.MapPost("/expenses/{id:guid}/approve", ApproveExpense)
    .RequireAuthorization("CanApproveExpense");

static async Task<IResult> ApproveExpense(
    Guid id, IExpenseService service, CancellationToken ct)
{
    return await service.ApproveAsync(id, ct)
        ? Results.NoContent()
        : Results.NotFound();
}

Testing strategy

Security tests must prove denied paths as carefully as allowed paths.

  • Use WebApplicationFactory with deterministic test identities without bypassing authorization middleware.
  • Test 401, 403, and non-disclosing inaccessible-resource behavior.
  • Cover wrong scope, role, tenant, owner, operation, and resource state.
  • Test wrong token issuer, audience, signature, lifetime, and algorithm where bearer tokens are used.
  • Assert responses and logs do not reveal tokens, secrets, claims, or protected object existence.

Security considerations

Identity configuration, keys, redirects, cookies, claims, and logs all belong to the security boundary.

  • Use a trusted standards-based provider and validate token signature, issuer, audience, lifetime, and algorithms.
  • Use short-lived access tokens and protect refresh tokens with rotation, reuse detection, and revocation procedures.
  • For cookies, use Secure, HttpOnly, appropriate SameSite, antiforgery protection, and protected shared data keys.
  • Minimize claims and never log authorization headers, cookies, token bodies, or unnecessary personal data.
  • Perform object and tenant authorization on the server even when gateways and UI layers restrict access.

Performance and scalability

Identity checks run on every protected request, but caching must not extend permissions beyond the accepted security window.

  • Use supported metadata and signing-key caches and test rollover.
  • Keep claims compact to limit header, proxy, logging, and serialization cost.
  • Bound remote introspection with timeouts and fail closed.
  • Cache authorization decisions only with subject, tenant, resource, operation, policy version, and safe TTL in the key.
  • Measure handler and policy latency without recording token data.

Deployment and operations

External URLs, proxy headers, key persistence, clocks, and issuer settings affect production identity behavior.

  • Validate authority, audience, callback paths, redirects, and external scheme against the real HTTPS hostname.
  • Persist and isolate data-protection keys for shared cookie deployments.
  • Synchronize clocks and rehearse signing-key rollover and provider degradation.
  • Use managed identity or workload federation for service credentials where supported.
  • Deploy authorization changes with audit telemetry, compatibility tests, and rollback.

Common problems and fixes

A protected endpoint returns 401.

Likely cause: No scheme authenticated the request or token validation failed.

Fix: Inspect safe diagnostics, scheme selection, issuer, audience, keys, lifetime, and challenge headers without logging the token.

An authenticated caller receives 403.

Likely cause: A policy requirement or resource handler did not succeed.

Fix: Verify the principal, policy, failed requirement, and exact user-resource-operation tuple.

Changing an ID exposes another tenant.

Likely cause: The endpoint authenticated but did not scope loading and authorize the resource.

Fix: Filter by tenant, authorize the loaded object, and add cross-tenant tests.

Cookie login loops behind a proxy.

Likely cause: Forwarded headers, HTTPS detection, callback paths, SameSite, or data keys are misconfigured.

Fix: Trust known proxies only and verify external URL, cookie attributes, and shared key storage.

Tokens fail after signing-key rotation.

Likely cause: Key metadata is stale or rollover overlap is insufficient.

Fix: Use supported refresh, retain overlapping valid keys, monitor rollover, and test it.

Permission removal is delayed.

Likely cause: A token or decision cache still contains the permission.

Fix: Shorten lifetime or use introspection/revocation when immediate removal is required.

Best practices

  • Validate issuer, audience, signature, lifetime, and algorithms for bearer access tokens.
  • Prefer policy and resource-based authorization over inline role checks.
  • Protect endpoints by default and review anonymous access.
  • Authorize the subject-resource-operation tuple within the tenant boundary.
  • Keep identity credentials and keys out of source and logs and rotate them.
  • Return deliberate 401, 403, or non-disclosing 404 outcomes.
  • Keep access tokens short-lived and claims minimal.
  • Test anonymous, invalid, wrong-scope, wrong-role, wrong-tenant, and non-owner callers.

Production checklist

  • Issuer, audience, signature, lifetime, algorithms, metadata endpoint, and clock skew are explicit.
  • Schemes, defaults, fallback policy, and every anonymous endpoint are reviewed.
  • Policies model business permissions and object or tenant checks authorize resources.
  • Cookies, refresh tokens, signing keys, client secrets, and data keys have protected storage and rotation.
  • 401, 403, and non-disclosing behavior is covered by negative tests.
  • Logs and telemetry exclude tokens, cookies, secrets, and unnecessary claims.
  • Rollover, provider outage, revoked access, emergency access, and compromise have runbooks.
  • The real proxy, HTTPS hostname, callbacks, cookies, and shared keys are smoke-tested.

Common interview questions

What is the difference between authentication and authorization?

Authentication verifies identity. Authorization evaluates whether that identity is permitted to perform an action on a resource.

Why are refresh tokens treated differently from access tokens?

Refresh tokens are longer-lived credentials used to obtain access tokens, so they require stronger storage, rotation, reuse detection, and revocation controls.

What is resource-based authorization?

It evaluates access using both the principal and the actual resource instance—for example, whether the current user owns a document.

What is the difference between 401 and 403?

401 means acceptable authentication is missing; 403 means an authenticated caller lacks permission.

Why is an ID token not an API access token?

It describes authentication to a client and is intended for that client, while an access token targets an API audience.

When should a fallback policy be used?

Use it when endpoints should be private unless explicitly marked anonymous.

Can JWT access be revoked immediately?

Self-contained tokens normally remain valid until expiry unless the system adds revocation or introspection, so lifetime must match the accepted window.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Authentication & Authorization Documents

A .NET 10 API demonstrating authentication challenge and forbid behavior, fallback policy, scope authorization, resource ownership, administrator override, non-disclosure, and negative HTTP tests.

ASP.NET Core 10AuthenticationPolicy AuthorizationxUnit
dedicated-samplefallback-policyresource-authorizationnegative-testing
Run
dotnet run --project src/AuthenticationAuthorizationDocuments
Test
dotnet test AuthenticationAuthorizationDocuments.slnx