ASP.NET Core Interview Question #144
What is CSRF and how does ASP.NET Core help prevent it?
Authentication, Authorization & Security Mid-Level Intermediate
Quick Interview Answer
Cross-Site Request Forgery (CSRF) occurs when a malicious site causes a victim's browser to send an unwanted state-changing request to another site where the browser automatically supplies credentials such as authentication cookies.
Detailed Explanation
Cross-Site Request Forgery (CSRF) occurs when a malicious site causes a victim's browser to send an unwanted state-changing request to another site where the browser automatically supplies credentials such as authentication cookies.
ASP.NET Core MVC provides anti-forgery tokens for browser form scenarios. The server verifies that the request contains the expected token before accepting the operation. State-changing actions should also use appropriate HTTP methods rather than GET.
Code Example
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ChangeEmail(ChangeEmailViewModel model)
{
// Perform validated state change.
return RedirectToAction("Profile");
}