CSRF and CORS
Browsers attach cookies automatically, so another site can trigger requests to yours. SameSite cookies and tokens stop that.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Cross-site request forgery tricks a signed-in user’s browser into sending a request to your site from a page they visited elsewhere; the browser adds your session cookie. Defences make such requests fail: SameSite cookies are not sent cross-site, and an anti-forgery token the other site cannot know must match. CORS is different: it controls which other origins may read responses, and it does not stop requests being sent.
Code
// Cookie the browser should not send on cross-site requests
options.Cookie.SameSite = SameSiteMode.Lax;
// Anti-forgery token in each form, checked on POST
builder.Services.AddAntiforgery();
app.MapPost("/transfer", Transfer).RequireAntiforgery();
// CORS: which other origins may READ your API's responses
policy.WithOrigins("https://app.example.com");Tips
- State-changing actions should use POST/PUT/DELETE, never GET.
- SameSite=Lax is the modern browser default and blocks most CSRF; tokens cover the rest.
- Never set CORS to allow any origin with credentials. CORS relaxes the same-origin policy; it doesn’t add protection.
In the .NET library
ASP.NET Core’s antiforgery middleware issues and validates tokens; Razor forms include them automatically.