Volume 2 · Chapter 8 — ASP.NET Core Enterprise Development

Authentication and Authorization

Goutham Mayaluri 8 min read .NETC#ASP.NET CoreAuthenticationAuthorization

8.1 Introduction

Security rests on two distinct concerns: authentication (who you are) and authorization (what you may do). ASP.NET Core provides a flexible security architecture supporting cookies, JWT bearer tokens, OAuth 2.0, OpenID Connect, and rich authorization policies. Volume 9 covers OAuth2/OIDC/JWT in architectural depth; this chapter focuses on how ASP.NET Core implements the security pipeline and the authorization models you apply in practice.

8.2 The Security Pipeline

Authentication middleware validates the request’s credentials and builds theClaimsPrincipal(the user with their claims), attaching it toHttpContext.User. Authorization middleware then evaluates whether that user may access the endpoint. This ordering - authenticate, then authorize - is why those middleware components must be registered in that sequence.

sequenceDiagram
  autonumber
  participant C as Client
  participant Auth as Authentication MW
  participant User as HttpContext.User
  participant Authz as Authorization MW
  participant EP as Endpoint
  C->>Auth: request + credentials (JWT/cookie)
  Auth->>Auth: validate credentials
  Auth->>User: build ClaimsPrincipal
  User->>Authz: identity available
  Authz->>Authz: evaluate policy/roles
  alt authorized
      Authz->>EP: proceed
  else denied
      Authz-->>C: 401 / 403
  end

8.3 Claims-Based Identity and JWT

Modern identity is claims-based: the authenticated user carries claims (name, roles, permissions, attributes) that authorization evaluates, rather than just a username. For APIs, JSON Web Tokens are the common mechanism because they are self-contained and enable stateless authentication - the API validates the token’s signature, issuer, audience, and expiry locally on each request without a session store.


builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = "https://login.microsoftonline.com/tenant/v2.0";  // fetches signing keys
        o.TokenValidationParameters = new()
        {
            ValidateIssuer = true, ValidateAudience = true,
            ValidAudience = "api://payments", ValidateLifetime = true   // reject expired
        };
    });

8.4 Role-Based vs Policy-Based Authorization

Role-based authorization checks membership in predefined roles - simple but coarse. Policy-based authorization is more flexible: a policy is a named set of requirements evaluated against the user’s claims, and can include custom handlers for complex, business-specific rules (transaction limits, account ownership, regional access).


builder.Services.AddAuthorization(o =>
    o.AddPolicy("CanApprovePayment", p => p.RequireClaim("permission", "payments.approve")));

[Authorize(Policy = "CanApprovePayment")]
[HttpPost("{id}/approve")]
public IActionResult Approve(Guid id) => Ok();

8.5 OAuth 2.0, OpenID Connect, and Refresh Tokens

OAuth 2.0 is a delegated authorization framework (obtain a token to access resources without sharing credentials); OpenID Connect adds authentication (an ID token proving who the user is) on top. Access tokens are kept short-lived and paired with revocable refresh tokens so users are not forced to re-authenticate constantly, while a compromised access token has a small window. These flows and their trade-offs are detailed in Volume 9.

Senior Interview Question

What is the difference between role-based and policy-based authorization, and when do you use each?

Role-based authorization checks whether the user belongs to one or more predefined roles - for example[Authorize(Roles = "Admin")]- which is simple and works well for coarse-grained access where a small set of roles cleanly captures who can do what. Its limitation is that roles are blunt: real authorization often depends on more than role membership (the amount of a transaction, whether the user owns the specific account, the user’s region or department, time of day), and encoding all that as an explosion of roles becomes unmanageable. Policy-based authorization is more flexible and is the recommended approach for anything beyond simple roles: a policy is a named set of requirements that are evaluated against the user’s claims and, via custom authorization handlers, against arbitrary context. So a policy can require a specific claim, combine multiple requirements, or run a custom handler that checks business-specific conditions - “the user’s approval-limit claim is at least the transaction amount,” “the user owns this account,” “the user’s region matches the resource’s region.” Policies decouple the authorization rule (defined once, named) from the endpoints that use it, and support resource-based authorization where the decision depends on the specific resource instance. So I use role-based authorization for straightforward, coarse access control with a few well-defined roles, and policy-based authorization whenever the rule is more nuanced - claim combinations, business logic, or resource-specific checks - which in enterprise systems (and especially finance) is most of the interesting authorization. Roles themselves often become just one of the claims a policy evaluates. Policy-based authorization is strictly more powerful and is where non-trivial authorization belongs.

Senior Interview Question

How does a resource API validate a JWT, and why is that stateless?

The API validates a JWT locally on each request without calling back to the identity provider, which is what makes it stateless. It verifies the token’s signature using the issuer’s public signing key (fetched and cached from the provider’s well-known metadata endpoint), confirming the token was issued by the trusted authority and hasn’t been tampered with, and it checks the standard claims: the issuer matches the expected authority, the audience matches this API (so a token minted for another service is rejected), and the token hasn’t expired (and isn’t used before its valid-from time), plus any required scopes or roles for the endpoint. Because the token is self-contained - it carries the user’s identity and claims, signed - the API needs no server-side session store and no per-request lookup to the identity provider; everything needed to trust the request is inside the token and verifiable with the cached public key. That statelessness is the big advantage: it scales horizontally (any instance can validate any token, no shared session state) and is fast (no network round trip per request). The trade-off is revocation: since the token is trusted until it expires, you can’t easily invalidate a specific token before expiry, which is why access tokens are kept short-lived and paired with revocable refresh tokens, so a compromised token has a small window and the refresh token can be revoked at the provider. In ASP.NET Core this validation is configured viaAddJwtBearerwithTokenValidationParameters(validate issuer, audience, lifetime, signature), and the framework does it automatically on each request. So JWT validation is signature-plus-claims verification done locally, which is stateless and scalable, with short token lifetimes compensating for the revocation limitation.

Principal Engineer Question

How do you secure enterprise APIs comprehensively?

I build defense in depth anchored on identity, treating security as a property of every layer rather than a gate at the edge. Authentication is centralized through an identity provider using OAuth2/OIDC, and each API validates tokens itself (signature, issuer, audience, expiry, scopes) rather than trusting network location - so even internal calls prove identity (Zero Trust). Authorization is least-privilege and policy-based: fine-grained policies evaluated against claims, with custom handlers for business rules like transaction limits and account ownership, enforced at each service that owns the resource, and I don’t rely solely on a gateway to authorize. Tokens are short-lived with revocable refresh tokens. Beyond identity, I validate all input at the boundary (treating it as untrusted) to prevent injection and over-posting, use parameterized queries / an ORM, and apply output encoding. All traffic is over TLS, and secrets live in a vault accessed via managed identity - never in code or config - with rotation and audit. I add rate limiting to protect against abuse and overload, and security headers and CORS restrictions appropriate to the clients. Everything security-relevant is logged and audited - authentication events, authorization failures, sensitive-data access, administrative actions - feeding monitoring and alerting so intrusions and anomalies are detected. I bake security into the delivery pipeline (SAST, dependency scanning, secret scanning) so vulnerabilities are caught early, and I use secure defaults and shared libraries so teams get security by default rather than reinventing it. And I keep it under governance with regular security reviews and threat modeling. The unifying idea is layered controls - strong authentication, least-privilege policy-based authorization enforced per service, input validation, encryption, secret management, rate limiting, and comprehensive auditing/monitoring - so that no single control is the only barrier and a breach of one layer is contained by the others, which is exactly what an enterprise (and a regulated financial API in particular) requires.

8.6 Enterprise Scenario

A banking platform secures its APIs with an identity provider issuing JWT access tokens validated locally by each service, claims-based identity, and policy-based authorization for sensitive operations. Payment approval requires a policy combining the user’s permission claim, account ownership (via a custom handler), and a transaction-limit check - so authorization reflects real business rules, not just roles. Short-lived access tokens with revocable refresh tokens, TLS everywhere, vault-managed secrets, rate limiting, and full audit logging complete a defense-in-depth posture.

Chapter Revision Notes

  • Authentication establishes identity (ClaimsPrincipal); authorization enforces access - in that order.
  • JWTs enable stateless API auth - validated locally (signature, issuer, audience, expiry).
  • Use policy-based authorization (claims + custom handlers) for anything beyond simple roles.
  • OAuth2 = delegated authorization; OIDC adds authentication; short-lived tokens + revocable refresh.
  • Secure comprehensively: per-service authz, input validation, TLS, vault secrets, rate limiting, audit.