Simple method to help prevent XSRF in an asp.net MVC4 application
7/25/2012Just saw a neat and incredibly easy way to help prevent XSRF. If you are unsure what a cross-site request forgery is, here is a poor and substandard summary:
"XSRF uses a browsers cookie session to hi-jack your authorization creditial on the site you are on to submit malicious things to that site"
More or less..
So if you have forms on your website (which most of us do) and it an area of the site that requires an authenticated user to submit the form, pay attention! First we add this Data Annotation to the Actionresult in the controller that is handling the HttpPost, like so:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(SomethingViewModel viewModel) { if (ModelState.IsValid) { //Do your save stuff here } return View(viewModel); }
Adding [ValidateAntiForgeryToken] is 50% of the work we have to do, now in the form that is being posted back you need to add an html helper:
@Html.AntiForgeryToken()
Make sure you add this inside the form. What it generates is a hidden field with a token that the controller will now validate against to make sure the request came from the right place and not from the bad guys. If you run your project and inspect the source it will look something like this:
name="__RequestVerificationToken"
type="hidden"
value="LYqnmnP8k_(...)_qT7Nt4LpARhU1">
I trimmed down the value field a bit for readability, but there it is. In two very simple steps you are adding a great security feature on your site.
Cheers,
{David Stanley}