📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is cross-site request forgery (CSRF)? When does using cookies make your app vulnerable, how does antiforgery work in ASP.NET Core MVC, Razor Pages and Minimal APIs, how should an SPA send the token, and how much does SameSite=Lax protect you on its own?

CSRF mechanics, when cookie authentication is exposed, ASP.NET Core antiforgery across MVC, Razor Pages, Minimal APIs and SPAs, and the limits of SameSite cookies.

Mid-Level Security Intermediate antiforgery aspnet-core cookies csrf samesite security

🎯 Key points

  • CSRF: the browser attaches ambient credentials (cookies) to a request another site triggers
  • Bearer tokens in an Authorization header aren't sent automatically, so pure token APIs aren't CSRF-prone
  • Synchroniser token: cookie token + form/header token, validated together by IAntiforgery
  • MVC: form tag helper emits __RequestVerificationToken; AutoValidateAntiforgeryToken globally; Razor Pages validate POSTs by default
  • Minimal APIs (introduced in .NET 8, unchanged in .NET 10): AddAntiforgery + UseAntiforgery after UseAuthentication/UseAuthorization; form-binding endpoints validate automatically
  • SPA: send token in a header (X-XSRF-TOKEN) from IAntiforgery.GetAndStoreTokens
  • SameSite=Lax blocks cross-site subresource and POST cookies but still sends them on top-level GET navigation and from same-site subdomains
  • Never change state on GET; protect login too; re-authenticate for high-value actions; XSS defeats every CSRF defence

⏱ 30-second answer

CSRF makes a victim's browser send a state-changing request to your site from another site; it works because the browser attaches cookies automatically. If you authenticate with cookies, you're exposed; if callers send a bearer token in the Authorization header, a cross-site page can't add it, so classic CSRF doesn't apply.

ASP.NET Core's antiforgery uses a synchroniser token: a cookie token plus a token in the form or a header, validated together. MVC forms get it from the form tag helper with [ValidateAntiForgeryToken] or the global auto-validate filter; Razor Pages validate POSTs by default; Minimal APIs need AddAntiforgery/UseAntiforgery and validate form-bound endpoints. SameSite=Lax (the default for ASP.NET Core auth cookies) blocks most cross-site POSTs, but not attacks from a sibling subdomain or GETs that change state, so keep tokens.

🗣 Full answer (senior)

How I would answer this in an interview

"CSRF is confused-deputy: my site trusts the browser because it carries the session cookie, and the browser will carry that cookie on a request that some other site started. A hidden auto-submitting form on evil.example posting to /account/email is enough if I rely on cookies and nothing else. So the first question I ask is how the app authenticates. If it's a cookie, I need CSRF protection. If it's a pure API where clients put a bearer token in the Authorization header, a cross-site page can't attach that header, so CSRF isn't the risk; XSS is.

ASP.NET Core's answer is the synchroniser token pattern. IAntiforgery issues a cookie token and a request token derived from the same secret, bound to the user, and protected with Data Protection. The form tag helper writes the request token as a hidden field, and validation checks the pair. In MVC I add AutoValidateAntiforgeryTokenAttribute globally so every unsafe method is covered. Razor Pages does it by default. Minimal APIs since .NET 8 have UseAntiforgery, which validates endpoints that bind forms. For a SPA using cookie auth through a BFF, I expose the token through a readable cookie and the client echoes it in an X-XSRF-TOKEN header. For example, at [company] we [moved our SPA to a BFF with cookies] and the first security review asked exactly this; header-based antiforgery closed it with [one middleware and an Axios interceptor].

The mistake I see is 'we have SameSite=Lax, we don't need tokens'. Lax blocks cross-site POSTs, but shop.example.com.au and blog.example.com.au are the same site, so a takeover of any subdomain bypasses it, and a GET that changes state is still exposed. SameSite is a great second layer, not the first."


When you need CSRF protection

Authentication CSRF risk Why
Cookie (MVC, Razor Pages, BFF) Yes Browser sends cookies automatically
Bearer token in Authorization header No (classic CSRF) Cross-site pages can't set that header
Windows/Kerberos/NTLM, client certificates Yes Also ambient credentials
Basic auth cached by the browser Yes Ambient

Vulnerable, exploit, fixed

  • Vulnerable: a Minimal API app.MapPost("/account/email", ([FromForm] string email, ...) => ...).DisableAntiforgery(); behind cookie auth, or an MVC action with [IgnoreAntiforgeryToken].
  • Exploit (one line): another site serves an auto-submitting form that POSTs email=attacker@... to /account/email; the victim's cookie rides along.
  • Fixed: remove DisableAntiforgery, call UseAntiforgery(), and render the token in the form (or send it in a header from the SPA).

ASP.NET Core antiforgery by app model

Model What's automatic What you do
MVC Form tag helper emits the token Add AutoValidateAntiforgeryTokenAttribute globally
Razor Pages Token emitted and validated for POST Nothing (don't add IgnoreAntiforgeryToken)
Minimal APIs (.NET 8+) Validates endpoints binding [FromForm]/IFormFile once UseAntiforgery runs Call AddAntiforgery/UseAntiforgery; for JSON + cookies validate explicitly
Blazor Web App <AntiforgeryToken /> in forms Keep UseAntiforgery after auth
SPA + BFF — Header token (X-XSRF-TOKEN) + IAntiforgery.ValidateRequestAsync

Production example

In a BFF rollout, adding header-based antiforgery and SameSite=Strict on the session cookie cost one extra cookie and a 10-line Axios interceptor; an OWASP ZAP scan that had flagged 14 state-changing endpoints for missing anti-CSRF tokens reported none afterwards.

🔍 What the interviewer is checking

Checks that the candidate links CSRF to ambient credentials, knows ASP.NET Core antiforgery across app models, and understands SameSite's limits.

Green flags

  • Starts with 'how does the app authenticate?'
  • Explains the synchroniser token and why the attacker can't read it
  • Knows Minimal API behaviour in .NET 8+ and header tokens for SPAs
  • Names SameSite gaps: subdomains, GET side effects

Red flags

  • Says CORS prevents CSRF
  • Disables antiforgery to fix errors
  • Thinks bearer-token APIs need antiforgery tokens but cookie apps don't

📚 Learn in depth

1. The attack

Victim logged in to bank.example.com.au (session cookie set)
      |
      | visits evil.example
      v
<form action="https://bank.example.com.au/transfer" method="post"> ... auto-submit
      |
      v
Browser POSTs to bank, attaching the bank cookie (if SameSite allows)
      |
      v
Bank sees a valid session -> performs the transfer

The attacker never sees the response; they only need the side effect. CORS doesn't stop it, because a form POST with application/x-www-form-urlencoded is a simple request and is sent without a preflight.

2. The synchroniser token pattern in ASP.NET Core

IAntiforgery (DefaultAntiforgery) generates:

  • a cookie token (.AspNetCore.Antiforgery.<id>), HttpOnly, containing a random security token;
  • a request token, containing the same security token plus the user identity (claim uid or name), so a token from one user can't be replayed by another.

Both are encrypted with Data Protection (purpose Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1). On validation, both are decrypted and compared. An attacker's site can make the browser send the cookie but can't read your page to get the request token, because the same-origin policy hides the response. That's the whole trick, and it's why XSS (which runs in your origin) defeats it.

This is also why antiforgery fails across instances when Data Protection keys aren't shared: the token was encrypted by another instance's key ring.

3. Minimal APIs in .NET 8+

AddAntiforgery() registers the services; UseAntiforgery() adds middleware that, for endpoints with antiforgery metadata, validates the request. Endpoints that bind [FromForm] or IFormFile get that metadata automatically. JSON endpoints don't, because the assumption is they're called with bearer tokens; if a JSON endpoint is cookie-authenticated, validate explicitly with IAntiforgery.ValidateRequestAsync or an endpoint filter. UseAntiforgery must come after UseAuthentication and UseAuthorization.

4. SameSite as a second layer

SameSite Cross-site POST Top-level cross-site GET navigation Same-site subdomain
Strict Not sent Not sent Sent
Lax Not sent Sent Sent
None (+Secure) Sent Sent Sent

ASP.NET Core's cookie authentication defaults to SameSite=Lax. Gaps: 'site' means registrable domain, so evil.example.com.au owned by a compromised subdomain is same-site; GET handlers with side effects are reachable via a link; and Chromium's 'Lax-by-default' for cookies without an explicit attribute allowed top-level cross-site POSTs for two minutes after the cookie was set, a known bypass window.

5. Other techniques

  • Origin/Referer checking: reject unsafe requests whose Origin isn't yours; good as an extra layer.
  • Fetch metadata (Sec-Fetch-Site: cross-site): modern browsers send it; a resource isolation policy can reject cross-site unsafe requests.
  • Re-authentication for very sensitive actions (change email, payments).
  • Login CSRF: protect the login form too, or an attacker can log the victim into the attacker's account.

Try it yourself

  1. Create an MVC form, remove the token from the HTML in dev tools and submit; read the 400 and the log entry.
  2. Build a page on another port that auto-posts to your Minimal API form endpoint; test with and without UseAntiforgery.
  3. Change the auth cookie between Lax, Strict and None and repeat the attack.
  4. Run two instances without shared Data Protection keys and watch antiforgery fail across them.
  5. Inspect Sec-Fetch-Site on same-origin and cross-site requests in dev tools.

💻 Code

Antiforgery for a cookie-authenticated app: global validation for MVC, Minimal API form endpoints, and header-based tokens for an SPA served by the same BFF.

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication("Cookies").AddCookie("Cookies", o =>
{
    o.Cookie.HttpOnly = true;
    o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    o.Cookie.SameSite = SameSiteMode.Strict;   // second layer, not the only one
});
builder.Services.AddAuthorization();
builder.Services.AddAntiforgery(o => o.HeaderName = "X-XSRF-TOKEN");
builder.Services.AddControllersWithViews(o =>
    o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));  // every POST/PUT/PATCH/DELETE

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();   // after auth

// Give the SPA a readable token cookie (the cookie token itself stays HttpOnly)
app.MapGet("/bff/antiforgery", (IAntiforgery af, HttpContext ctx) =>
{
    var tokens = af.GetAndStoreTokens(ctx);
    ctx.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken!,
        new CookieOptions { HttpOnly = false, Secure = true, SameSite = SameSiteMode.Strict });
    return Results.NoContent();
}).RequireAuthorization();

// JSON endpoint authenticated by cookie: validate explicitly
app.MapPost("/bff/account/email", async (EmailChange body, IAntiforgery af, HttpContext ctx, CancellationToken ct) =>
{
    await af.ValidateRequestAsync(ctx);       // throws AntiforgeryValidationException -> 400
    // ... change the email
    return Results.NoContent();
}).RequireAuthorization();

// Form endpoint: validated automatically because it binds [FromForm]
app.MapPost("/newsletter", ([FromForm] string email) => Results.Ok()).RequireAuthorization();

app.MapDefaultControllerRoute();
app.Run();

public sealed record EmailChange(string NewEmail);
// SPA: Axios echoes the token cookie into the header on unsafe requests
axios.defaults.xsrfCookieName = 'XSRF-TOKEN';
axios.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
axios.defaults.withXSRFToken = true;

⚠ Common mistakes

  • Mistake: Adding [IgnoreAntiforgeryToken] or DisableAntiforgery() to 'fix' 400 errors. Why it is wrong: it removes the protection instead of fixing the client. Instead: send the token from the form or header, and fix Data Protection key sharing if it fails across instances.
  • Mistake: Relying on SameSite=Lax alone. Why it is wrong: same-site subdomains, state-changing GETs and older browsers bypass it. Instead: keep antiforgery tokens and use SameSite as a second layer.
  • Mistake: Changing state on GET (/orders/42/cancel via link). Why it is wrong: Lax cookies are sent on top-level GET navigation and antiforgery isn't validated for GET. Instead: use POST/PUT/DELETE for side effects.
  • Mistake: Adding antiforgery to a pure bearer-token API. Why it is wrong: it adds friction without addressing a real risk. Instead: rely on the header token; focus on XSS and token storage.
  • Mistake: Assuming Minimal API JSON endpoints are validated by UseAntiforgery. Why it is wrong: only form-binding endpoints get antiforgery metadata automatically. Instead: validate explicitly when JSON endpoints use cookie auth.
  • Mistake: Thinking CORS prevents CSRF. Why it is wrong: simple form POSTs are sent without preflight; CORS only hides the response. Instead: use antiforgery tokens.
  • Mistake: Leaving the login form unprotected. Why it is wrong: login CSRF signs the victim into the attacker's account and captures their activity. Instead: validate antiforgery on login too.

🏛 Senior insight: trade-offs

The senior question is 'what credential does the browser send without being asked?' If the answer is nothing (bearer tokens in headers), CSRF largely disappears and XSS becomes the threat to tokens. If the answer is a cookie (which the BFF pattern deliberately chooses, to keep tokens out of JavaScript), CSRF protection is mandatory, and you layer it: antiforgery token, SameSite=Strict or Lax, Origin or Fetch-Metadata checks, and re-authentication for high-value actions.

Defence When it fits Cost Limitation
Synchroniser token (IAntiforgery) Any cookie-authenticated app Token plumbing, Data Protection key sharing Defeated by XSS
SameSite=Strict Session cookies of apps not entered via cross-site links Users arriving from emails appear logged out on first request Same-site subdomains
SameSite=Lax Default for most apps None GET side effects, subdomains
Origin / Sec-Fetch-Site checks Extra layer for APIs and BFFs Small middleware Older clients may omit headers
Re-authentication Payments, credential changes User friction Only for high-value actions

Measure: count of endpoints with antiforgery disabled (should be near zero and justified), antiforgery validation failures in logs (a spike means a client bug or an attack), and ZAP findings.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions SameSite or HttpOnly cookie flags Why: Checks the full cookie authentication picture, including Data Protection's role
    How to answer

    After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.

  2. When: Candidate mentions a BFF or an API accepting both cookies and JWTs Why: Checks they can design mixed cookie and token authentication without opening CSRF holes
    How to answer

    Put a single identity provider in the middle (Entra External ID, Auth0 or a self-hosted OIDC server) that federates Google and Apple; every app speaks only OIDC to it, so adding a login provider never touches your code.

    • SPA: a BFF (ASP.NET Core) runs the code flow as a confidential client, keeps tokens server-side and gives the browser an HttpOnly, SameSite cookie; it proxies API calls with an access token.
    • Mobile: authorisation code + PKCE in the system browser (RFC 8252), tokens in Keychain/Keystore, rotating refresh tokens.
    • API: accepts JWT bearer only. The BFF and mobile apps both send tokens, so the API never needs cookies. If one host must accept both, use a policy scheme that forwards by header, plus CSRF protection for cookie requests.

    The trade-off: a BFF adds a hop and state, in exchange for no tokens in the browser.

🛠 Real-world problems: how you handle them

Pen test flags missing CSRF protection after a move to a BFF
Situation
A React SPA was moved from tokens in the browser to a backend-for-frontend with an HttpOnly session cookie to meet [a security review / client requirement]. The API behind the BFF serves [number] users and handles [payments / account changes].
Signals
Pen test and OWASP ZAP report 'Absence of Anti-CSRF Tokens' on [14] state-changing endpoints; a proof-of-concept page on another domain changes a test user's email; no antiforgery failures in logs because nothing validates.
Investigation
Confirmed the session cookie was `SameSite=None` (set for an old cross-site iframe) and that JSON endpoints accepted cookies with no token. Reviewed which callers used cookies versus bearer tokens. Tested the PoC with Burp Suite against each endpoint and checked `Sec-Fetch-Site` and `Origin` headers in captured traffic.
Resolution
Immediate: set the session cookie to `SameSite=Lax`, which blocked the PoC. Real fix: added `IAntiforgery` with header-based tokens validated by an endpoint filter on every unsafe BFF route, an Axios interceptor on the client, and an Origin check middleware as an extra layer; moved the session cookie to `Strict` once the iframe was retired.
Prevention
Integration tests that send unsafe requests without the header and expect 400; a ZAP baseline scan in the pipeline; a review checklist item: 'cookie-authenticated endpoint => antiforgery'; alert on spikes in antiforgery validation failures.

How to tell it (STAR)

**S:** At [company] we moved our SPA to a BFF with a session cookie, and the next pen test flagged [14] endpoints as CSRF-vulnerable with a working PoC. **T:** I had to close it before [the go-live date] without breaking the client. **A:** I found the cookie was `SameSite=None` for a legacy iframe and that nothing validated tokens on JSON routes. I switched to Lax as an immediate block, then added header-based antiforgery through an endpoint filter, an Axios interceptor and an Origin check. **R:** The retest showed zero CSRF findings, the change was [about 50 lines], and our pipeline now fails if a cookie-authenticated unsafe endpoint skips validation.

↩ Usually asked after

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me