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?
When you create a new 'Web Form Application' project in VS 2013, the site.master.cs will automatically include the XSRF/CSRF code in the
Page_Init
section of the class. If you still dont get the generated code, you can manuallyCopy
+Paste
the code. If you are using C#, then use the below:-You could use below piece of code, which will check the request where it is coming from
It works great for me!!!
ViewStateUserKey & Double Submit Cookie
Starting with Visual Studio 2012, Microsoft added built-in CSRF protection to new web forms application projects. To utilize this code, add a new ASP .NET Web Forms Application to your solution and view the Site.Master code behind page. This solution will apply CSRF protection to all content pages that inherit from the Site.Master page.
The following requirements must be met for this solution to work:
All web forms making data modifications must use the Site.Master page. All requests making data modifications must use the ViewState. The web site must be free from all Cross-Site Scripting (XSS) vulnerabilities. See how to fix Cross-Site Scripting (XSS) using Microsoft .Net Web Protection Library for details.
You could try the following. In the Web-Form add:
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:
AntiForgery.Validate();
throws an exception if anti XSFR check fails.