CSRF and CORS

Browsers attach cookies automatically, so another site can trigger requests to yours. SameSite cookies and tokens stop that.

Time O(1)Space O(1)Code C#
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

In the .NET library

ASP.NET Core’s antiforgery middleware issues and validates tokens; Razor forms include them automatically.