Join our Newsletter — 33% off our NHI Course
Home› Guides› ASP.NET Core Security Guide: Data Protection, Antiforgery, Identity…
Guide Application Security

ASP.NET Core Security Guide: Data Protection, Antiforgery, Identity and Authorisation Policies

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 8 November 2026 14 min read
On this page

Most serious ASP.NET Core security defects are not framework bugs but framework features left at defaults that suit a developer laptop rather than a production farm. Data Protection keys that live in one container, a fallback authorisation policy that is null, antiforgery that never runs because the project called AddControllers(), and Identity lockout that the sign-in code quietly switches off. This guide goes below the broad advice in the .NET Security Guide and covers the ASP.NET Core runtime controls themselves: the Data Protection key ring, antiforgery, ASP.NET Core Identity, policy and resource-based authorisation, JWT bearer validation, HTTPS and HSTS, and the secrets the app uses to reach other services. It is written for application security engineers, .NET leads and platform teams who review or own ASP.NET Core services on .NET 8 and later.

This is an independent guide from NHI Mgmt Group, based on Microsoft's public documentation as of November 2026. It is not sponsored or reviewed by Microsoft. Product features change, so confirm settings against Microsoft's current documentation.

Key takeaways

  • The Data Protection key ring is a crown-jewel secret. It protects authentication cookies, antiforgery tokens and TempData, so anyone who can write to the repository can mint sessions; persist it to a shared store, encrypt it at rest and restrict it to the app identity.
  • Authorisation is open by default. FallbackPolicy is null, so an endpoint with no metadata is anonymous; set a fallback that requires an authenticated user and mark public endpoints with AllowAnonymous.
  • Attributes cannot see the object. [Authorize] runs before model binding, so ownership checks need imperative IAuthorizationService.AuthorizeAsync with the loaded resource, or broken object level authorisation follows.
  • Antiforgery has gaps by design. The middleware validates POST, PUT and PATCH only, does not short-circuit, and controllers registered with AddControllers() get no tokens at all.
  • Identity defaults are a starting point. Lockout only counts failures when the sign-in call passes lockoutOnFailure: true, and password, cookie and security stamp settings need deliberate values.

How identity and access work in ASP.NET Core

ASP.NET Core separates three concerns that teams often blur. Authentication handlers (cookie, JWT bearer, OpenID Connect, Windows) turn a request into a ClaimsPrincipal. Authorisation evaluates policies made of requirements against that principal and, optionally, a resource. Data Protection is the cryptographic subsystem that makes cookie tickets and antiforgery tokens tamper-proof. ASP.NET Core Identity is an optional membership system on top: user store, password hashing, lockout, two-factor and tokens for email confirmation and password reset. For the wider .NET picture (supported versions, deserialisation, NuGet), see the .NET Security Guide.

Policy evaluation rules worth memorising

Endpoint metadataPolicy appliedSecurity consequence
NoneFallbackPolicy (null by default)Endpoint is anonymous unless a fallback is configured
[Authorize] or RequireAuthorization() with no nameDefaultPolicy (authenticated user)Any signed-in user passes, including low-privilege ones
[Authorize(Policy = "X")]Named policy XSeveral attributes combine: all must pass
[Authorize(Roles = "A,B")]Policy built from the rolesComma list means any one role; stacked attributes mean all
[AllowAnonymous]No authorisation failure enforcedOverrides controller and fallback policies; audit every use
  • Requirements and handlers: requirements inside one policy combine with AND; several handlers for the same requirement combine with OR, so one permissive handler satisfies the requirement. A handler that must veto calls context.Fail(), which guarantees failure even if another handler succeeds.
  • Handler order: handlers run in no guaranteed order and still run when authentication failed, so never assume context.User is authenticated inside a handler.
  • Short-circuiting: InvokeHandlersAfterFailure defaults to true. Set it to false only if handlers are expensive and you understand that later handlers will not log.
  • Static files: files served by UseStaticFiles before the authorisation middleware are not covered by the fallback policy. Keep sensitive files out of wwwroot.

Resource-based authorisation

Microsoft's documentation is explicit that attribute evaluation happens before data binding and before any method that loads the resource, so [Authorize] alone cannot decide whether user 42 may read invoice 9001. Load the object, then call AuthorizeAsync(User, invoice, Operations.Read) with an AuthorizationHandler<OperationAuthorizationRequirement, Invoice>. Return 403 (Forbid) for an authenticated user who fails, 401 (Challenge) when there is no identity, and consider 404 where revealing existence leaks data. This is the code-level fix for OWASP API1; see the OWASP API Top 10 API1 Broken Object Level Authorization Guide and the Authorisation Testing Automation Guide for how to keep it from regressing.

Admin roles and privileged access

ASP.NET Core has no built-in "admin" concept: administrative power is whatever your roles, claims and policies say it is. That makes three things privileged.

  • Administrative endpoints: group them (an /admin area, a minimal API route group) and apply a named policy at the group level, for example a policy requiring an admin role claim plus an amr or authentication-method claim that shows phishing-resistant MFA. Applying the policy once to the group is safer than relying on every developer to decorate every action.
  • Role and claim issuance: whoever can write roles to the Identity store, or change claim mapping from the identity provider, controls admin access. Restrict UserManager.AddToRoleAsync paths to a dedicated, audited flow, and set MapInboundClaims = false on JWT bearer so claim names arrive as issued rather than remapped to long URIs that policies then mismatch.
  • Revocation speed: cookie sessions carry roles until they are revalidated. ASP.NET Core Identity's security stamp validator re-checks the stamp at SecurityStampValidatorOptions.ValidationInterval; call UpdateSecurityStampAsync when you remove a role or reset a password, and shorten the interval for admin applications so removal takes effect within minutes (ASVS 5.0 V8.3.2 asks that changes to authorisation inputs apply immediately or are bounded).
  • Operational access: anyone with write access to the Data Protection key repository, the Key Vault holding app secrets or the deployment slot can impersonate users. Treat those as privileged roles in your cloud IAM and PAM model. See the Privileged Access Management Guide.

ASP.NET Core Identity settings to change from default

SettingDocumented defaultRecommended production value
Password.RequiredLength6At least 8 with MFA, 15 for single-factor (NIST SP 800-63B guidance); relax composition rules and add a breached-password check
Lockout.MaxFailedAccessAttempts55 to 10, combined with rate limiting by IP and account
Lockout.DefaultLockoutTimeSpan5 minutes15 minutes or progressive back-off
PasswordSignInAsync(..., lockoutOnFailure)Template samples pass falsetrue, otherwise failures never count
SignIn.RequireConfirmedEmailfalsetrue for self-registration
PasswordHasherOptions.IterationCount100,000 (PBKDF2, IdentityV3 format)Keep at or above the current default; raise as hardware allows
SecurityStampValidatorOptions.ValidationIntervalConfigurableShort (for example 1 to 5 minutes) for admin apps

If authentication is delegated to an external identity provider over OpenID Connect, most of these move to the IdP; ASP.NET Core then only needs cookie lifetime, claim mapping and token validation right. See the Password Hashing and Key Derivation Guide for iteration choices.

Integrations, API tokens and service accounts

The Data Protection key ring

Data Protection is the most under-managed secret in most ASP.NET Core estates. Its documented defaults depend on where the app runs:

Hosting environmentDefault key locationEncrypted at restProduction risk
Azure App Service%HOME%\ASP.NET\DataProtection-Keys, shared within one slotNoSlot swap can sign every user out; keys readable by anyone with site file access
Windows with user profile%LOCALAPPDATA%\ASP.NET\DataProtection-KeysYes, DPAPIKeys differ per machine in a farm
IIS without profileHKLM registry key ACLed to the worker processYes, DPAPINot shared across nodes
Containers and other fallback casesIn memory onlyNot applicableEvery restart or new replica invalidates cookies and antiforgery tokens
  • Persist centrally: PersistKeysToAzureBlobStorage (with a managed identity, no SAS), PersistKeysToDbContext or a persistent Redis. Every node must read the same repository and use the same SetApplicationName value.
  • Encrypt at rest explicitly: changing the repository disables automatic encryption, so add ProtectKeysWithAzureKeyVault (identity needs Get, Wrap Key and Unwrap Key, for example via the Key Vault Crypto User role, and a versionless key identifier if Key Vault rotation is on) or ProtectKeysWithCertificate with UnprotectKeysWithAnyCertificate for certificate rollover.
  • Isolate: Microsoft warns that apps sharing a key repository are not isolated from each other even with different discriminators, and that at-rest encryption does not stop an attacker with write access inserting a key. Give each trust boundary its own repository and give write access only to the app identity.
  • Lifetime: keys roll every 90 days by default (SetDefaultKeyLifetime); retired keys stay in the ring for decryption. Do not delete old keys while protected payloads with long lives exist. Use DisableAutomaticKeyGeneration on secondary apps so only one app manages the ring.

Outbound secrets and app identity

  • Configuration secrets: keep connection strings and API keys out of appsettings.json. Use the Secret Manager (dotnet user-secrets) in Development only and the Azure Key Vault configuration provider (AddAzureKeyVault) or an equivalent vault provider in production, with ManagedIdentityCredential rather than a client secret. Secret names use -- for hierarchy; ReloadInterval is null by default, so rotated secrets are not picked up until restart unless you set it.
  • Service-to-service calls: prefer workload identity (managed identity, federated credentials) over stored client secrets; where OAuth client credentials are needed, use certificate or private_key_jwt client authentication. See the Machine-to-Machine OAuth (Client Credentials) Guide.
  • Inbound tokens: for APIs, AddJwtBearer with Authority and Audience validates signature, issuer, audience and expiry from metadata. Use the defaults; never set ValidateIssuer, ValidateAudience or ValidateIssuerSigningKey to false outside an isolated test environment, and keep test token flows and Swagger UI out of production. For several issuers use AddPolicyScheme to select a scheme rather than loosening validation. See the JWT Security Guide.

Logging and detection

ASP.NET Core emits structured logs through ILogger; the useful security signals sit in the Microsoft.AspNetCore.Authentication, Microsoft.AspNetCore.Authorization and antiforgery categories, which are often filtered out at the default Warning level. Raise them to Information for security-relevant services and ship them to your SIEM with the user identifier, client IP (after forwarded headers) and trace ID.

SignalSourceWhat it can indicate
Authorisation failures per user and routeAuthorization log category; custom handler loggingObject ID enumeration (BOLA probing), privilege probing
Bearer token validation failures (bad audience, issuer, signature)JwtBearer events OnAuthenticationFailedToken replay from another tenant or forged tokens
Cookie unprotect failures after deploymentData Protection and cookie authentication logsKey ring not shared, or a key inserted or removed
Antiforgery validation failuresAntiforgery logs (logged in Production, thrown in Development)CSRF attempts or a broken front end
Lockouts and failed sign-insIdentity SignInResult.IsLockedOut, custom audit eventsPassword spraying or credential stuffing (ATT&CK T1110)
Writes to the key repository or Key Vault keyStorage and Key Vault diagnostic logsKey insertion that would allow forged sessions

Metrics that show the controls are working:

  • Percentage of endpoints covered by a named policy or the fallback policy (target 100 percent, measured from endpoint metadata at start-up or in tests).
  • Count of AllowAnonymous and DisableAntiforgery uses, each with a recorded justification.
  • Authorisation regression tests per sensitive resource type, and their pass rate in CI.
  • Mean time from role removal to effective denial (bounded by the security stamp interval).
  • Number of services whose Data Protection keys are persisted centrally and encrypted at rest.

Hardening baseline

  • Authorisation by default: AddAuthorizationBuilder().SetFallbackPolicy(...RequireAuthenticatedUser()), named policies for sensitive operations, resource handlers for owned objects.
  • Antiforgery for every cookie-authenticated, browser-reachable endpoint: use AddControllersWithViews() and a global AutoValidateAntiforgeryTokenAttribute; for minimal APIs keep form-binding protection on and check IAntiforgeryValidationFeature or call IAntiforgery.ValidateRequestAsync explicitly, including for DELETE. Set Cookie.SecurePolicy = CookieSecurePolicy.Always. Bearer-only APIs that never read cookies do not need antiforgery. See the CSRF Prevention Guide.
  • Cookies: authentication cookies HttpOnly, Secure, an explicit SameSite value chosen for the flow (ASVS 5.0 V3.3.2), bounded ExpireTimeSpan.
  • Transport: UseForwardedHeaders before UseHttpsRedirection behind a proxy; UseHsts outside Development, starting with a short MaxAge and raising it to a year once stable. For APIs, do not redirect: listen on HTTPS only or reject HTTP with 400.
  • Errors: developer exception page in Development only; UseExceptionHandler and problem details without stack traces in production.
  • Middleware order: routing, CORS, authentication, authorisation, antiforgery, then endpoints. Misordering silently disables controls.

Rolling it out

  1. Inventory: list endpoints and their authorisation metadata (a start-up test that enumerates EndpointDataSource works well) and every Data Protection configuration.
  2. Fix the key ring first: move to a shared, encrypted repository. Deploy to one slot or replica first and confirm existing sessions still decrypt; roll back by restoring the previous repository, which still holds the old keys.
  3. Add the fallback policy in audit mode: in a test environment, enable it and run the full integration suite; every newly failing public endpoint gets an explicit AllowAnonymous after review.
  4. Add resource handlers for the highest-value objects (accounts, payments, documents), with two-user tests (user A cannot read user B's object).
  5. Turn on antiforgery globally and fix front ends that fail; ship to a pilot ring with antiforgery failures alerting.
  6. Tighten Identity and cookies, then monitor lockout and sign-in metrics for a week before raising thresholds further.

Decision guidance: small teams with one app on App Service can use Blob Storage plus Key Vault and the built-in Identity; larger estates should delegate authentication to a central IdP, keep ASP.NET Core Identity out of new services, and consider externalised authorisation where many services share rules (see the Externalised Authorisation Buyer's Guide). Cookie authentication with antiforgery suits server-rendered apps and a backend-for-frontend; bearer tokens suit APIs called by other services.

Framework mapping

ASP.NET Core controlNIST SP 800-53 Rev. 5NIST CSF 2.0OWASP ASVS 5.0ATT&CK addressed
Fallback, named and resource policiesAC-3, AC-6PR.AA-05V8.2.2, V8.3.2T1190
Data Protection key ring managementSC-12PR.DS-02V3.3.2 (cookies it protects)T1539
Antiforgery and cookie attributesSC-23PR.PS-06V3.3.2T1539
Identity passwords and lockoutIA-5PR.AA-05V16.3.2 (logging of failures)T1110
Vaulted configuration secretsIA-5PR.PS-06n/aT1552.001
HTTPS and HSTSSC-8PR.DS-02n/an/a
Security loggingAU-2PR.PS-04V16.3.2n/a

Common misconfigurations

  • In-memory keys in containers: every pod restart signs everyone out, so teams "fix" it by pinning sessions or extending cookie lifetimes instead of persisting the ring.
  • Key repository shared across environments: staging and production reading one Blob container means a staging compromise forges production cookies.
  • Role check instead of ownership check: [Authorize(Roles = "Customer")] on GET /orders/{id} lets any customer read any order. Use resource-based authorisation to check ownership on every request, and monitor response volumes per caller.
  • Lockout configured but never triggered: lockoutOnFailure: false copied from samples means MaxFailedAccessAttempts does nothing.
  • Antiforgery assumed: APIs built with AddControllers() that also accept the auth cookie, or DELETE endpoints behind the middleware, are unprotected.
  • Validation turned off to make a test pass: ValidateAudience = false accepts tokens minted for any other API from the same issuer.

Practitioner checklist

  • Persist Data Protection keys to one shared store per trust boundary, encrypt them with Key Vault or a certificate, and restrict write access to the app identity.
  • Set a consistent SetApplicationName across nodes and never share a repository across environments.
  • Configure a fallback policy requiring authenticated users and review every AllowAnonymous.
  • Use resource-based handlers for every owned object and test them with two users.
  • Enable antiforgery globally for cookie-authenticated endpoints and validate DELETE explicitly.
  • Pass lockoutOnFailure: true, raise password length and add breached-password checks, or delegate to an IdP.
  • Keep JWT bearer validation at defaults with Authority and Audience; set MapInboundClaims = false deliberately.
  • Load secrets from a vault with managed identity and set a reload interval that matches rotation.
  • Enable HSTS and HTTPS-only listening, with forwarded headers first behind proxies.
  • Log authentication, authorisation and antiforgery failures to the SIEM and track the metrics above.

Standards and references

Related NHI Mgmt Group resources: .NET Security Guide · Broken Access Control Prevention Guide · CSRF Prevention Guide · Token and Session Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 8 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.