How to protect your ASP.NET WebForms application against CSRF (Cross-Site Request Forgery) attacks?

It’s important to defend your ASP.NET application against CSRF attacks. Otherwise, your users may perform unwanted data changes in their accounts without even knowing it. This data change could be a profile update or a big money transfer!

First of all, what is CSRF (Cross-Site Request Forgery)? According to OWASP:

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated.

Solution

Microsoft added built-in CSRF protection starting from Visual Studio 2012. If you have a project that was created with an earlier version of Visual Studio, no worries! You can protect your application by simply adding this method in your code-behind files.

protected override OnInit(EventArgs e) {
     base.OnInit(e);
     ViewStateUserKey = Session.SessionID;
}

We used to need to set ViewStateMAC parameter to true but not anymore!

References

Leave a Reply