CSRF (Cross-Site Request Forgery) Handling in MVC

Phil Haack's talk on asp.net reminded me of the importance of handling CSRF attacks. In MVC, this is simply handled with a one-two punch. In your posting form, you need to include the Html.AntiForgeryToken() in the form as follows:

  

The other thing is to add an [ValidateAntiForgeryToken] attribute to the targeted posting action in your controller as follows:
[ValidateAntiForgeryToken]
[HttpPost] 
// or MVC 1.0 style [AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Delete(FormCollection form, int id) {
  // code here to delete stuff
  return View();
}
Also don't forget that we want to make sure that any state-changing operations are always posts!
My new syntax highlighting is accomplished via a method outlined on Carter Cole's most excellent blog.

Comments

Popular posts from this blog

Database Projects, SQL Unit Tests, and TeamCity

Brent: Programmer. Gamer. Cheapskate. All around good guy.

Building nice XML from SQL Server Tables