Nerdly Things

.tech and personal blog of david stanley.

Simple method to help prevent XSRF in an asp.net MVC4 application

7/25/2012

Just 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}

Back to Blog
Adriana
Date Posted: 8/27/2012
This is detached scraenio. If you want to save changes in entities and in relations you must say EF what changes were executed. EF doesn't know it and it doesn't perform any automatic synchronization with the state in the database. This problemetic is known also as working with detached object graphs and in my opinion it is the biggest complexity in entity framework (and probably ORM globally). I answered and you can also found .General answer is you must know which relations were created or removed and you must manually set either state of related object (in case of one-to-one or one-to-many) or state of relation (in case many-to-many). The complexity is even worse if you have many-to-many and you can create relation to existing objects, create new related objects or delete existing related objects in the same request.My general advice is using less elegant but much easier approach: load your entity graph from the database and merge incomming changes into attached graph.

Add a comment