Solved: “Validation of viewstate MAC failed”

You may come across this error message when you get around in pages of your ASP.NET website:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Background

ASP.NET uses view-state variable to rebuild pages after post-backs. The text of your buttons and the value of the form fields are the examples that this variable stores.

In order to prevent tempering attacks that try to play around with view-state data to force your webpage behave unexpectedly, web server validates the view-state data between page redirections. If the data doesn’t match, you receive the error message above.

Solution

The issue of unmatched view-state data could be related to server configuration or session cookie. Here are the most common root causes:

  • Web server and application pool configuration related issues. Read details in this Microsoft Support article
  • If you are using ViewStateUserKey to prevent Cross-site Request Forgery (CSRF) attacks, make sure the value you assign to this variable is the same in all pages. The most common usage is that assigning session ID or username to ViewStateUserKey. Your website might be losing the session between page redirections. Check these two StackOverflow topics for details: Link 1link 2
  • Redirecting the page right after setting session variables may be the issue. You should avoid using Response.Redirect in this case. Details
  • Antivirus software might be causing the issue. Add scanning exceptions for IIS and your application’s folders. Details

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