0

We are using new ASP.NET Web forms template in new VS 2012. Because we had some problems on IIS, with this error:

"System.Web.HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. ---> System.Web.UI.ViewStateException: Invalid viewstate."

Then we made this changes to web.config:

<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" enableViewStateMac="false" > ... </pages>

but, then we got the error: "Validation of Anti-XSRF token failed."

We then commented all the code in Site.Master.cs, regarding Anti-XSRF token validation (because site is used on intranet), however now we cannot login using IE (in Chrome and Firefox works), because after login (which is succesfull in log), it redirects to login page again, but the user is logged in.

UPDATE I tried all of the solutions from here and it doesn't work: http://blogs.msdn.com/b/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx. Lastly, I tried also with: in web.config, but then i get the error: System.InvalidOperationException: Validation of Anti-XSRF token failed. Still, there is no solution.

UPDATE 2 Is there a proper way to disable Anti-XSRF token validation in new ASP.NET Web Forms template project ?

Milan
  • 85
  • 2
  • 10

1 Answers1

2

Instead of disactivaving all the security features of ASP.NET (which is NOT advised at all), you should rather focus on solving the actual error.

System.Web.HttpException (0x80004005): Validation of viewstate MAC failed is a common error. To solve it, you have to define a machinekey to use in your web.config file. This is usually due to the fact that you have two different keys across postback. Defining one in the web.config will most likely solve the issue (do not forget to reactivate security features like viewstate encryption). You can generate one here: http://aspnetresources.com/tools/machineKey

See this post for an example: https://stackoverflow.com/a/6260201/375304 (but do NOT use the same key).

Also, have look at this link, it might be helpful to understand ASP.NET security features related to the machinekey. http://msdn.microsoft.com/en-us/library/ff649308.aspx

UPDATE: If any of this doesn't work, try the following (source):

Another solution based on #3 above, special thanks to Alex for posting this in the comments below. He wrote a small class called BasePage that fixes the issues, so you just have to extend your page from BasePage instead of Page:

public class BasePage : Page
{
  private static string[] aspNetFormElements = new string[] 
  { 
    "__EVENTTARGET",
    "__EVENTARGUMENT",
    "__VIEWSTATE",
    "__EVENTVALIDATION",
    "__VIEWSTATEENCRYPTED",
  };

  protected override void Render(HtmlTextWriter writer)
  {
    StringWriter stringWriter = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    base.Render(htmlWriter);
    string html = stringWriter.ToString();
    int formStart = html.IndexOf("<form");
    int endForm = -1;
    if (formStart >= 0)
      endForm = html.IndexOf(">", formStart);

    if (endForm >= 0)
    {
      StringBuilder viewStateBuilder = new StringBuilder();
      foreach (string element in aspNetFormElements)
      {
        int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
        if (startPoint >= 0 && startPoint > endForm)
        {
          int endPoint = html.IndexOf("/>", startPoint);
          if (endPoint >= 0)
          {
            endPoint += 2;
            string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
            html = html.Remove(startPoint, endPoint - startPoint);
            viewStateBuilder.Append(viewStateInput).Append("\r\n");
          }
        }
      }

      if (viewStateBuilder.Length > 0)
      {
        viewStateBuilder.Insert(0, "\r\n");
        html = html.Insert(endForm + 1, viewStateBuilder.ToString());
      }
    }

    writer.Write(html);
  }
}
Community
  • 1
  • 1
Superzadeh
  • 1,106
  • 7
  • 23
  • Regarding the first error ("Validation of viewstate MAC failed"), we tried everything and failed. Of course, we tried with defining machinekey in web.config, actually, it is generated with the new project, but it not working. – Milan Oct 09 '13 at 08:16
  • Well, then you should review your code and see if there isn't anything modifying the viewstate on POSTs. But I still strongly advise you to solve the MAC validation issue rather than the login/redirect problem. – Superzadeh Oct 09 '13 at 08:25
  • I returned everything to default state, and now I'm getting the same error on IIS: "Validation of viewstate MAC failed.", Client IP: 192.168.80.156 Port: 7401 Referer: http://app_server/myapp/Account/Login.aspx?ReturnUrl=%2fmyapp Path: /myapp/Account/Login.aspx User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko ViewState: 2bpxzxMEz... Locally, it works done. What can modify viewstate on POST ? – Milan Oct 09 '13 at 08:39
  • Have you tried the last solution described [here](http://blogs.msdn.com/b/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx) ? See the update for a cleaner, inheritance of base page solution. – Superzadeh Oct 09 '13 at 08:47
  • The first two solutions doesn't work, I may try this third solution. Which of my pages should extend this BasePage (Login, Default, SiteMaster, ...) ? – Milan Oct 09 '13 at 09:08
  • All of the content pages (not the master page) – Superzadeh Oct 09 '13 at 09:12
  • I tried to extend my Login page and Default page with this BasePage, and the error is still there. – Milan Oct 09 '13 at 09:13
  • Is your Windows Server updated ? There has been KB to fix this (KB 361949 I think). – Superzadeh Oct 09 '13 at 09:16
  • Cannot find this hotfix. Our Windows Server 2008 R2 SP1 is automatically updated, regulary. – Milan Oct 09 '13 at 09:22
  • Do you have Databounds controls on the pages where you encounter the issue ? – Superzadeh Oct 09 '13 at 09:25
  • I tried also with: in web.config, but then i get the error: System.InvalidOperationException: Validation of Anti-XSRF token failed. We lost 5 days because of this issue :(. No, no databound controls, we are using simple login page that redirects to the emtpy default page with menu. – Milan Oct 09 '13 at 09:27
  • Anti-XSRF token validation could be done in your masterpage with some JavaScript code. Could you check it and make sure it is removed ? – Superzadeh Oct 09 '13 at 09:31
  • I already tried to remove this Anti-XSRF token validation from SiteMaster codebehind, but then I have problem with login in IE, i.e., user cannot login, it always redirects to login page. – Milan Oct 09 '13 at 09:36
  • Could you fiddler to try and determine what happens redirection wise (when does the redirect happens -- on which get --) ? – Superzadeh Oct 09 '13 at 09:38
  • When I disable Anti-XSRF token validation in SiteMaster and in IE click on login there are four results: 302 (POST /myapp/Account/Login.aspx?ReturnUrl=%2myapp) HTTP/1.1, then again 302 (GET /myapp HTTP/1.1), then 200 (GET /myapp/Account/Login.aspx?ReturnUrl=%2fmyapp HTTP/1.1) and again 200 (GET /myapp/Account/Login.aspx?_TSM_CombinedScripts_=True&v=BxMJl2YsD-7Va5GUx1XW6vrMFpWkz3rf7xov9zs1dOo1&_TSM_Bundles_= HTTP/1.1). – Milan Oct 09 '13 at 09:44
  • Have you tried clearing / disabling your browser caches and cookies ? – Superzadeh Oct 09 '13 at 09:47
  • In your browser, press ctrl+shift+del, it should open a window, check everything (except "preserve for favorites yadiyadiyada" in IE) and click delete. – Superzadeh Oct 09 '13 at 09:52
  • I tried this in IE, but it just redirects to Login page. In Chrome it works! Regarding IE, in our log file, it says that user IS logged in (from LoginUser_LoggedIn), but in IE, it just redirects to login page. – Milan Oct 09 '13 at 09:54
  • I could not reproduce that on my local environment. However, seeing that the XSRF token is stored in the ViewState, my guess would be that something on your page somehow modifies the viewstate before it is posted, resulting in both errors. – Superzadeh Oct 09 '13 at 10:09
  • What can modify viewstate ? And why this works in Chrome and FF and not in IE ? – Milan Oct 09 '13 at 10:18
  • That, I have no idea. – Superzadeh Oct 09 '13 at 11:10
  • Isn't IE's security settings blocking the cookie ? – Superzadeh Oct 09 '13 at 16:21
  • I dobut, because we tried on IE 9 (Win7), IE 10 (Win7) and IE 11 (Win8), on three different machines. I made a mistake, there is a cookie, but in the case of IE, after 302 (GET /myapp HTTP/1.1), login page is returned, instead of default page, as it is case of Chrome na FF. – Milan Oct 09 '13 at 19:41