skip to content

Built-In Security Defenses

The protections ASP.NET Core ships beyond sign-in: CORS policies, antiforgery tokens, HTTPS redirection with HSTS, the rate limiter and the Data Protection key ring. Interviewers probe each default.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

25

In ASP.NET Core Razor Pages, what protects a charity's donation form from forged cross-site posts, and what is checked when it is submitted?

level: juniorimportance: must knowfreq 66%

answer

  1. two halves that must pair
  2. cookie .AspNetCore.Antiforgery.<hash>
  3. hidden field __RequestVerificationToken
  4. AutoValidateAntiforgeryToken on every page
  5. failure: 400 Bad Request

basics

~20 s

Razor Pages validates antiforgery tokens on every unsafe request automatically: the form carries a request token in __RequestVerificationToken, the browser returns a cookie token, and IAntiforgery checks that they pair and match the user. A failure returns 400.

solid answer

~40 s

`AddRazorPages()` registers the antiforgery services for you, and Razor Pages adds an `[AutoValidateAntiforgeryToken]` filter to every page, so any request other than GET, HEAD, OPTIONS or TRACE is validated before the handler runs. When the donation page renders its `<form method="post">`, ASP.NET Core issues two tokens: a **cookie token** in a cookie named `.AspNetCore.Antiforgery.<hash>` (HttpOnly, SameSite=Strict) and a **request token** in the hidden `__RequestVerificationToken` field. On submit, `IAntiforgery.ValidateRequestAsync` reads the cookie and the request token (from the `RequestVerificationToken` header or the form field), decrypts both with Data Protection, and checks that they share one security token and that the request token was issued to the current user. Any failure stops the handler with `400 Bad Request`; nothing is stored in session state.

code

csharp · 14 lines
csharp
public class DonateModel(IDonationService donations) : PageModel
{
    [BindProperty]
    public decimal Amount { get; set; }

    public void OnGet() { }

    public async Task<IActionResult> OnPostAsync()
    {
        // Reached only if the cookie token and __RequestVerificationToken pair up.
        await donations.RecordAsync(Amount);
        return RedirectToPage("/Thanks");
    }
}

go deeper

for a junior

Recall the pair: a cookie token and a hidden __RequestVerificationToken field, checked automatically on Razor Pages posts, with 400 on failure.

for a middle

Explain how AddRazorPages registers the services, how the page model gets AutoValidateAntiforgeryToken, which methods it skips, and how the request token binds to the user.

for a senior

Know when a page must opt out with [IgnoreAntiforgeryToken], what replaces the token there, and how cookie, header and caching options affect behaviour behind proxies and CDNs.

for a principal

Weigh relying on framework-issued tokens across many apps against a shared cookie name, key ring and policy, and decide who owns exemptions such as provider callbacks.

## The two tokens ASP.NET Core issues ASP.NET Core's antiforgery system (`Microsoft.AspNetCore.Antiforgery`) protects form posts with a **token pair**. Neither half is useful alone: - The **cookie token** travels in a cookie whose name starts with `.AspNetCore.Antiforgery.` followed by a short hash of the app's Data Protection discriminator. By default the cookie is `HttpOnly`, `SameSite=Strict`, marked essential, and has no expiry, so it is a browser-session cookie. - The **request token** is written into the page, as a hidden `<input name="__RequestVerificationToken">` in the form. A script can send it in a `RequestVerificationToken` header instead. - Both are produced by the singleton `IAntiforgery` service and encrypted with **Data Protection**, so they cannot be read or forged without the app's keys. The request token embeds the same random security token as the cookie token, plus the identity of the signed-in user (a claims-based id or the user name). That binding is why a token rendered for one user does not validate for another. ## Where Razor Pages switches validation on You write no attribute for a donation page: 1. `builder.Services.AddRazorPages()` calls `AddAntiforgery()` internally, registering `IAntiforgery` and its options. 2. When Razor Pages builds each page's model, it adds an **`[AutoValidateAntiforgeryToken]`** filter unless the page already carries an antiforgery policy such as `[IgnoreAntiforgeryToken]`. 3. The form tag helper adds the hidden field to the post forms it renders (how it decides is the tag helpers' business). `AutoValidateAntiforgeryToken` skips **GET, HEAD, OPTIONS and TRACE** and validates every other method, so `OnPost`, `OnPostRefundAsync` and the rest are all covered. ## What the check does on submit `IAntiforgery.ValidateRequestAsync(HttpContext)` runs in an authorization filter before the handler: 1. Read the cookie token from the antiforgery cookie. 2. Read the request token from the header named by `AntiforgeryOptions.HeaderName` (default `RequestVerificationToken`); if there is none and the body is a form, read the `__RequestVerificationToken` field. 3. Decrypt both tokens. 4. Confirm the cookie token and request token carry the same security token, and that the request token's user matches `HttpContext.User`. If any step fails, an `AntiforgeryValidationException` is caught and the filter sets an `AntiforgeryValidationFailedResult`, which is a **`400 Bad Request`**. The handler never runs. | Failure | Message the system records | |---|---| | no cookie | The required antiforgery cookie "..." is not present. | | no field or header | The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken". | | tokens from different pairs | The antiforgery cookie token and request token do not match. | | wrong user | The provided antiforgery token was meant for a different claims-based user than the current user. | ## Opting a page out A page that receives posts from a non-browser caller, such as a payment provider's server-to-server notification, cannot present a token. Put **`[IgnoreAntiforgeryToken]`** on its `PageModel` class; Razor Pages filters apply to the whole page, not to individual handler methods. That page then needs its own proof of origin, such as a signature check. ## What you can configure `builder.Services.AddAntiforgery(options => ...)` adjusts `AntiforgeryOptions`: - `Cookie`: a `CookieBuilder` for the name, `SecurePolicy`, `SameSite` and path. - `FormFieldName`: the hidden field name, `__RequestVerificationToken` by default. - `HeaderName`: the header read first, `RequestVerificationToken` by default; `null` means form only. - `SuppressXFrameOptionsHeader`: by default, a response that sets a new antiforgery cookie also gets `X-Frame-Options: SAMEORIGIN` unless the header is already present. Responses that issue tokens are also marked `Cache-Control: no-cache, no-store`, because a cached form would hand one visitor's token to another.

  • How do you exempt one Razor Page, such as a payment provider's server-to-server callback, from ASP.NET Core's automatic antiforgery check?
    Put `[IgnoreAntiforgeryToken]` on that page's `PageModel` class. Razor Pages sees an existing antiforgery policy and does not add `[AutoValidateAntiforgeryToken]`. Filters apply per page, not per handler method, so give the callback its own page, and verify the caller another way, for example by checking the provider's request signature.
  • Why does the hidden __RequestVerificationToken value change on every render while the ASP.NET Core antiforgery cookie stays the same?
    `GetAndStoreTokens` reuses a valid cookie token instead of issuing a new one, then creates a fresh request token that embeds the same security token. Each request token is encrypted again by Data Protection, so its text differs every time, yet any of them pairs with the cookie. Two open tabs therefore both submit successfully.

  • Razor Pages forms are unprotected until each handler gets [ValidateAntiForgeryToken].
  • A failed antiforgery check returns 403 Forbidden.
  • The antiforgery cookie alone proves the post came from the site's own form.
  • ASP.NET Core stores the expected antiforgery token in session state.
  • Razor Pages validates antiforgery tokens on GET handlers too.
open as a page

In ASP.NET Core 10, how do you let a React storefront served from another origin call your API, and what does each CORS call do?

level: juniorimportance: must knowfreq 78%

basics

~10 s

Register a policy with builder.Services.AddCors(o => o.AddPolicy("Storefront", p => p.WithOrigins("https://shop.coffee.example"))) and apply it with app.UseCors("Storefront"). The policy tells browsers which origins may read responses; it blocks no other client.

open as a page

In ASP.NET Core, what is the Data Protection API for, and why does IDataProtectionProvider.CreateProtector require a purpose string?

level: juniorimportance: must knowfreq 45%

basics

~20 s

ASP.NET Core's Data Protection API encrypts and authenticates payloads that leave the server, such as auth cookies, antiforgery tokens and your own tokens. The purpose string isolates them: a payload protected under one purpose throws CryptographicException when unprotected under another.

open as a page

In ASP.NET Core, what do UseHttpsRedirection and UseHsts each do, and why do the web templates call UseHsts only outside Development?

level: juniorimportance: must knowfreq 64%

basics

~10 s

UseHttpsRedirection answers plain-HTTP requests with a 307 redirect to the HTTPS URL; UseHsts adds a Strict-Transport-Security header, 30 days by default, to HTTPS responses. Browsers cache HSTS, so the templates skip it in Development.

open as a page

In ASP.NET Core 10, which three calls put a named fixed-window rate limit on one Minimal API endpoint, and what breaks without each?

level: juniorimportance: must knowfreq 45%

basics

~10 s

Register a named policy with AddRateLimiter and AddFixedWindowLimiter, add the middleware with app.UseRateLimiter(), and attach the policy with RequireRateLimiting or [EnableRateLimiting]. UseRateLimiter without AddRateLimiter throws at startup; an unattached policy limits nothing.

open as a page

In ASP.NET Core MVC, how do [ValidateAntiForgeryToken], [AutoValidateAntiforgeryToken] and [IgnoreAntiforgeryToken] differ, and which would you register globally?

level: middleimportance: must knowfreq 58%

basics

~10 s

[ValidateAntiForgeryToken] validates every request, GET included; [AutoValidateAntiforgeryToken] skips GET, HEAD, OPTIONS and TRACE; [IgnoreAntiforgeryToken] turns validation off. The one closest to the action wins, so register AutoValidateAntiforgeryToken globally.

open as a page

Why does an ASP.NET Core CORS policy combining AllowAnyOrigin with AllowCredentials throw, and how do you let the storefront send cookies instead?

level: middleimportance: must knowfreq 64%

basics

~10 s

AllowAnyOrigin makes the policy answer Access-Control-Allow-Origin: *, which browsers never accept on a credentialed request, so CorsPolicyBuilder.Build() throws InvalidOperationException. List the storefront with WithOrigins and add AllowCredentials.

open as a page

Three load-balanced instances of an ASP.NET Core travel-agency site log every user out on each deploy; why, and how do you configure Data Protection to stop it?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Each container keeps its own Data Protection keys in its filesystem, so cookies from one instance fail on another and all fail after a redeploy. Persist keys to shared storage, protect them at rest, and set one application name.

open as a page

In ASP.NET Core, why does AddFixedWindowLimiter give every caller one shared counter, and how would you limit a weather API's free tier per user and per IP?

level: seniorimportance: must knowfreq 50%

basics

~10 s

AddFixedWindowLimiter keys its limiter on the policy name, so all callers share it. Use AddPolicy with a partitioner returning RateLimitPartition.GetFixedWindowLimiter keyed on the user name, or on Connection.RemoteIpAddress for anonymous callers.

open as a page

What does dotnet dev-certs https --trust do for local ASP.NET Core development, and when do you reach for --check, --clean or --export-path?

level: juniorimportance: should knowfreq 36%

basics

~20 s

The .NET SDK creates an ASP.NET Core HTTPS development certificate for localhost but does not trust it; dotnet dev-certs https --trust adds it to the trusted stores so browsers accept https://localhost. --check tests it, --clean removes it, --export-path copies it out.

open as a page

In ASP.NET Core 10 Minimal APIs, why does a form-binding endpoint need AddAntiforgery and UseAntiforgery, and what does DisableAntiforgery change?

level: middleimportance: should knowfreq 46%

basics

~20 s

Since ASP.NET Core 8, a Minimal API parameter bound from a form makes the endpoint require antiforgery. AddAntiforgery registers the services, UseAntiforgery runs the validating middleware (still not automatic in 10), and DisableAntiforgery removes the requirement.

open as a page

In ASP.NET Core 10, when UseCors, RequireCors and [EnableCors] or [DisableCors] all apply to one endpoint, which decides its CORS behaviour?

level: middleimportance: should knowfreq 42%

basics

~20 s

Endpoint metadata wins: [DisableCors] switches CORS off, RequireCors or [EnableCors("name")] picks that policy, and only otherwise does the policy given to UseCors (or the default policy) apply. An unknown policy name just yields no CORS headers.

open as a page

In ASP.NET Core Data Protection, what happens when the default key reaches its 90-day lifetime, and why do existing auth cookies keep working?

level: middleimportance: should knowfreq 35%

basics

~20 s

About two days before the default key's 90-day expiry, ASP.NET Core writes a successor that activates when the old key expires. Old keys stay in the ring and can still unprotect, so cookies protected with them keep working.

open as a page

In ASP.NET Core, how do you make a protected token such as a booking-change link expire with ITimeLimitedDataProtector, and what happens after expiry?

level: middleimportance: should knowfreq 30%

basics

~10 s

Call ToTimeLimitedDataProtector() on an IDataProtector, then Protect(value, TimeSpan.FromHours(24)). Unprotect(token, out expiration) returns the value until then; afterwards it throws CryptographicException ("The payload expired at ..."). The token can still be replayed until it expires.

open as a page

What does the AllowedHosts setting in an ASP.NET Core appsettings.json do, and how should a production app configure host filtering?

level: middleimportance: should knowfreq 38%

basics

~10 s

AllowedHosts feeds the host filtering middleware that WebApplication adds automatically: requests whose Host header is not in the semicolon-separated list get 400. The template's "*" disables it; production should list its real host names.

open as a page

How does ASP.NET Core's UseHttpsRedirection choose the redirect status and the HTTPS port, and why might it not redirect at all?

level: middleimportance: should knowfreq 44%

basics

~10 s

The status comes from HttpsRedirectionOptions.RedirectStatusCode, 307 unless you set 308. The port comes from HttpsPort, then HTTPS_PORT configuration, then the server's https address; with none, it logs a warning and does not redirect.

open as a page

In ASP.NET Core, how do AddFixedWindowLimiter, AddSlidingWindowLimiter, AddTokenBucketLimiter and AddConcurrencyLimiter differ in what they count and how you configure them?

level: middleimportance: should knowfreq 45%

basics

~20 s

Fixed window, sliding window and token bucket cap requests per time period; the concurrency limiter caps requests in flight at once. Each takes its own options class (Window, SegmentsPerWindow, TokensPerPeriod, PermitLimit), and all queue nothing unless QueueLimit is set.

open as a page

In ASP.NET Core, how do RateLimiterOptions.GlobalLimiter and an endpoint's named rate limiting policy combine on one request, and what does [DisableRateLimiting] switch off?

level: middleimportance: should knowfreq 35%

basics

~10 s

GlobalLimiter runs on every request first, then the endpoint's policy; the request proceeds only if both grant a permit. [DisableRateLimiting] or DisableRateLimiting() removes all limits from that endpoint, including the global limiter.

open as a page

Donation posts on an ASP.NET Core Razor Pages site intermittently return 400 Bad Request; how do you find which antiforgery check failed, and what does each failure point to?

level: seniorimportance: should knowfreq 34%

basics

~10 s

Raise logging for Microsoft.AspNetCore.Mvc.ViewFeatures.Filters to Information and read the 'Antiforgery token validation failed' message. A missing cookie, missing request token, user mismatch and decryption failure each point to a different cause.

open as a page

How do you give a JavaScript front end ASP.NET Core antiforgery tokens for cookie-authenticated fetch calls, and what does AntiforgeryOptions.HeaderName change?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Call IAntiforgery.GetAndStoreTokens in an endpoint, hand the returned RequestToken to the script, and have it send the value in the header named by AntiforgeryOptions.HeaderName (RequestVerificationToken by default). HeaderName renames that header; null disables header tokens.

open as a page

The storefront's console shows a CORS error, yet the ASP.NET Core API logged 200 and saved the subscription change — why, and how do you diagnose the policy?

level: seniorimportance: should knowfreq 38%

basics

~10 s

ASP.NET Core's CORS middleware never rejects a request: for a disallowed origin it just omits the Access-Control headers, the endpoint still runs, and the browser hides the response. Diagnose with Microsoft.AspNetCore.Cors logs at Information.

open as a page

In an ASP.NET Core CORS policy, how do you safely allow credentialed calls from every tenant storefront's own subdomain to the coffee-subscription API?

level: seniorimportance: should knowfreq 27%

basics

~10 s

Use WithOrigins("https://*.shops.coffee.example") with SetIsOriginAllowedToAllowWildcardSubdomains, or SetIsOriginAllowed with a predicate that checks the parsed origin against your tenant list, plus AllowCredentials. Never approve every origin.

open as a page

In ASP.NET Core, what breaks when the Data Protection key ring is lost or must be revoked after a leak, and what can you still recover?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Lost keys sign everyone out, fail pending antiforgery tokens and empty TempData, and make anything your app stored with Protect permanently unreadable. After a leak, RevokeAllKeys forces new keys; trusted stored data can be re-protected via DangerousUnprotect.

open as a page

Rolling HSTS out on a pharmacy refill site with ASP.NET Core, how would you set AddHsts's MaxAge, IncludeSubDomains, Preload and ExcludedHosts?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Start with a short MaxAge (hours to a day), raise it once HTTPS is stable, enable IncludeSubDomains only when every subdomain serves HTTPS, set Preload only before deliberately submitting the domain, and add exact host names to ExcludedHosts.

open as a page

In ASP.NET Core 10, why does a request the rate limiter rejects get 503, and how do you send 429 with a Retry-After value instead?

level: seniorimportance: should knowfreq 55%

basics

~10 s

RateLimiterOptions.RejectionStatusCode defaults to StatusCodes.Status503ServiceUnavailable. Set it to Status429TooManyRequests, and in OnRejected read MetadataName.RetryAfter from context.Lease to write a Retry-After header.

open as a page