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.
FallbackPolicyis null, so an endpoint with no metadata is anonymous; set a fallback that requires an authenticated user and mark public endpoints withAllowAnonymous. - Attributes cannot see the object.
[Authorize]runs before model binding, so ownership checks need imperativeIAuthorizationService.AuthorizeAsyncwith 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 metadata | Policy applied | Security consequence |
|---|---|---|
| None | FallbackPolicy (null by default) | Endpoint is anonymous unless a fallback is configured |
[Authorize] or RequireAuthorization() with no name | DefaultPolicy (authenticated user) | Any signed-in user passes, including low-privilege ones |
[Authorize(Policy = "X")] | Named policy X | Several attributes combine: all must pass |
[Authorize(Roles = "A,B")] | Policy built from the roles | Comma list means any one role; stacked attributes mean all |
[AllowAnonymous] | No authorisation failure enforced | Overrides 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.Useris authenticated inside a handler. - Short-circuiting:
InvokeHandlersAfterFailuredefaults 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
UseStaticFilesbefore the authorisation middleware are not covered by the fallback policy. Keep sensitive files out ofwwwroot.
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
/adminarea, a minimal API route group) and apply a named policy at the group level, for example a policy requiring anadminrole claim plus anamror 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.AddToRoleAsyncpaths to a dedicated, audited flow, and setMapInboundClaims = falseon 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; callUpdateSecurityStampAsyncwhen 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
| Setting | Documented default | Recommended production value |
|---|---|---|
Password.RequiredLength | 6 | At least 8 with MFA, 15 for single-factor (NIST SP 800-63B guidance); relax composition rules and add a breached-password check |
Lockout.MaxFailedAccessAttempts | 5 | 5 to 10, combined with rate limiting by IP and account |
Lockout.DefaultLockoutTimeSpan | 5 minutes | 15 minutes or progressive back-off |
PasswordSignInAsync(..., lockoutOnFailure) | Template samples pass false | true, otherwise failures never count |
SignIn.RequireConfirmedEmail | false | true for self-registration |
PasswordHasherOptions.IterationCount | 100,000 (PBKDF2, IdentityV3 format) | Keep at or above the current default; raise as hardware allows |
SecurityStampValidatorOptions.ValidationInterval | Configurable | Short (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 environment | Default key location | Encrypted at rest | Production risk |
|---|---|---|---|
| Azure App Service | %HOME%\ASP.NET\DataProtection-Keys, shared within one slot | No | Slot swap can sign every user out; keys readable by anyone with site file access |
| Windows with user profile | %LOCALAPPDATA%\ASP.NET\DataProtection-Keys | Yes, DPAPI | Keys differ per machine in a farm |
| IIS without profile | HKLM registry key ACLed to the worker process | Yes, DPAPI | Not shared across nodes |
| Containers and other fallback cases | In memory only | Not applicable | Every restart or new replica invalidates cookies and antiforgery tokens |
- Persist centrally:
PersistKeysToAzureBlobStorage(with a managed identity, no SAS),PersistKeysToDbContextor a persistent Redis. Every node must read the same repository and use the sameSetApplicationNamevalue. - 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) orProtectKeysWithCertificatewithUnprotectKeysWithAnyCertificatefor 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. UseDisableAutomaticKeyGenerationon 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, withManagedIdentityCredentialrather than a client secret. Secret names use--for hierarchy;ReloadIntervalis 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_jwtclient authentication. See the Machine-to-Machine OAuth (Client Credentials) Guide. - Inbound tokens: for APIs,
AddJwtBearerwithAuthorityandAudiencevalidates signature, issuer, audience and expiry from metadata. Use the defaults; never setValidateIssuer,ValidateAudienceorValidateIssuerSigningKeyto false outside an isolated test environment, and keep test token flows and Swagger UI out of production. For several issuers useAddPolicySchemeto 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.
| Signal | Source | What it can indicate |
|---|---|---|
| Authorisation failures per user and route | Authorization log category; custom handler logging | Object ID enumeration (BOLA probing), privilege probing |
| Bearer token validation failures (bad audience, issuer, signature) | JwtBearer events OnAuthenticationFailed | Token replay from another tenant or forged tokens |
| Cookie unprotect failures after deployment | Data Protection and cookie authentication logs | Key ring not shared, or a key inserted or removed |
| Antiforgery validation failures | Antiforgery logs (logged in Production, thrown in Development) | CSRF attempts or a broken front end |
| Lockouts and failed sign-ins | Identity SignInResult.IsLockedOut, custom audit events | Password spraying or credential stuffing (ATT&CK T1110) |
| Writes to the key repository or Key Vault key | Storage and Key Vault diagnostic logs | Key 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
AllowAnonymousandDisableAntiforgeryuses, 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 globalAutoValidateAntiforgeryTokenAttribute; for minimal APIs keep form-binding protection on and checkIAntiforgeryValidationFeatureor callIAntiforgery.ValidateRequestAsyncexplicitly, including for DELETE. SetCookie.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 explicitSameSitevalue chosen for the flow (ASVS 5.0 V3.3.2), boundedExpireTimeSpan. - Transport:
UseForwardedHeadersbeforeUseHttpsRedirectionbehind a proxy;UseHstsoutside Development, starting with a shortMaxAgeand 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;
UseExceptionHandlerand problem details without stack traces in production. - Middleware order: routing, CORS, authentication, authorisation, antiforgery, then endpoints. Misordering silently disables controls.
Rolling it out
- Inventory: list endpoints and their authorisation metadata (a start-up test that enumerates
EndpointDataSourceworks well) and every Data Protection configuration. - 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.
- 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
AllowAnonymousafter review. - Add resource handlers for the highest-value objects (accounts, payments, documents), with two-user tests (user A cannot read user B's object).
- Turn on antiforgery globally and fix front ends that fail; ship to a pilot ring with antiforgery failures alerting.
- 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 control | NIST SP 800-53 Rev. 5 | NIST CSF 2.0 | OWASP ASVS 5.0 | ATT&CK addressed |
|---|---|---|---|---|
| Fallback, named and resource policies | AC-3, AC-6 | PR.AA-05 | V8.2.2, V8.3.2 | T1190 |
| Data Protection key ring management | SC-12 | PR.DS-02 | V3.3.2 (cookies it protects) | T1539 |
| Antiforgery and cookie attributes | SC-23 | PR.PS-06 | V3.3.2 | T1539 |
| Identity passwords and lockout | IA-5 | PR.AA-05 | V16.3.2 (logging of failures) | T1110 |
| Vaulted configuration secrets | IA-5 | PR.PS-06 | n/a | T1552.001 |
| HTTPS and HSTS | SC-8 | PR.DS-02 | n/a | n/a |
| Security logging | AU-2 | PR.PS-04 | V16.3.2 | n/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")]onGET /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: falsecopied from samples meansMaxFailedAccessAttemptsdoes 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 = falseaccepts 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
SetApplicationNameacross 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
AuthorityandAudience; setMapInboundClaims = falsedeliberately. - 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
- Microsoft Learn: Configure ASP.NET Core Data Protection
- Microsoft Learn: Data Protection key management and lifetime
- Microsoft Learn: Policy-based authorization in ASP.NET Core
- Microsoft Learn: Resource-based authorization in ASP.NET Core
- Microsoft Learn: Prevent Cross-Site Request Forgery attacks in ASP.NET Core
- Microsoft Learn: Configure ASP.NET Core Identity
- Microsoft Learn: Enforce HTTPS in ASP.NET Core
- OWASP: Application Security Verification Standard 5.0
Related NHI Mgmt Group resources: .NET Security Guide · Broken Access Control Prevention Guide · CSRF Prevention Guide · Token and Session Security Guide