Let's see an example of a simple controller that may be susceptible to an XSRF/CSRF attack.
At first glance, everything feels safe and secure but, in the following, we'll see how a controller with code such as this can be mouthwatering to an XSRF/CSRF hacker:
public class ContactController : Controller
{
public ViewResult ContactDetails()
{ return View(); }
public ViewResult Update()
{
Contact contact = DbContext.GetContact();
contact.ContactId = Request.Form["ContactId"];
contact.Name = Request.Form["Name"];
SaveContact(contact);
return View();
}
}
Consider a scenario where a hacker sets up a page that deliberately targets this kind of controller. The hacker can then persuade a user to visit their page, which will then try to post to this controller. This controller will not be able to pick up the intended XSRF/CSRF attack when the user has already been authenticated via forms-based authentication or Windows authentication. See the following code:
<body onload="document.getElementById('contactForm').submit()">
<form id="contactForm" action="http://.../Contact/Update"
method="post">
<input name="ContactId" value="123456" />
<input name="Name" value="My Hack Example" />
</form>
</body>
This kind of attack is mitigated in different ways, as elaborated on in the next section.