preventing cross-site request forgery (csrf) attacks in asp.net web forms

Nada N. Hantouli picture Nada N. Hantouli · Apr 29, 2015 · Viewed 62.8k times · Source

I have created an ASP.Net Web Forms application using Visual Studio 2013 and I am using .NET Framework 4.5. I want to make sure my site is secure from Cross-Site Request Forgery (CSRF), I have found many articles talking about how this feature is implemented on MVC apps, but very few talking about Web Forms. On this StackOverflow question one comment states that

"This is an old question, but the latest Visual Studio 2012 ASP.NET template for web forms includes anti-CSRF code baked into the master page. If you don't have the templates, here's the code it generates:..."

My master page does not contain the code mentioned in that answer. Is it really included in new applications? If not, what is the best way to add it?

Answer

Saftpresse99 picture Saftpresse99 · Mar 22, 2016

You could try the following. In the Web-Form add:

<%= System.Web.Helpers.AntiForgery.GetHtml() %>

This will add a hidden field and a cookie. So if you fill out some form data and post it back to the server you need a simple check:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
        AntiForgery.Validate(); // throws an exception if anti XSFR check fails.
}

AntiForgery.Validate(); throws an exception if anti XSFR check fails.