title: How to Implement Anti XSRF token in ASP.net 3.5
body: <p>i have added the Anti Xsrf Token code generated by VS 2012 in .Net web application in frame work 3.5, On Submission of any form in Application i got the error :</p>
  
  <blockquote>
    <p>System.Web.HttpException: 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.    <a href="http://go.microsoft.com/fwlink/?LinkID=314055" rel="nofollow">http://go.microsoft.com/fwlink/?LinkID=314055</a> ---> System.Web.UI.ViewStateException: Invalid viewstate.    Client IP: 
            Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
        Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
        Dim _antiXsrfTokenValue As String</p>
  </blockquote>
  
  <pre><code>Protected Sub Page_Init(sender As Object, e As System.EventArgs)
      ' The code below helps to protect against XSRF attacks
      Dim requestCookie As HttpCookie = Request.Cookies(AntiXsrfTokenKey)
      Dim requestCookieGuidValue As Guid
      If ((Not requestCookie Is Nothing) AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue)) Then
          ' Use the Anti-XSRF token from the cookie
          _antiXsrfTokenValue = requestCookie.Value
          Page.ViewStateUserKey = _antiXsrfTokenValue
      Else
          ' Generate a new Anti-XSRF token and save to the cookie
          _antiXsrfTokenValue = Guid.NewGuid().ToString("N")
          Page.ViewStateUserKey = _antiXsrfTokenValue
  
          Dim responseCookie As HttpCookie = New HttpCookie(AntiXsrfTokenKey) With {.HttpOnly = True, .Value = _antiXsrfTokenValue}
          If (FormsAuthentication.RequireSSL And Request.IsSecureConnection) Then
              responseCookie.Secure = True
          End If
          Response.Cookies.Set(responseCookie)
      End If
  
      AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
  End Sub
  
  Private Sub master_Page_PreLoad(sender As Object, e As System.EventArgs)
      If (Not IsPostBack) Then
          ' Set Anti-XSRF token
          ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
          ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
      Else
          ' Validate the Anti-XSRF token
          If (Not DirectCast(ViewState(AntiXsrfTokenKey), String) = _antiXsrfTokenValue _
              Or Not DirectCast(ViewState(AntiXsrfUserNameKey), String) = If(Context.User.Identity.Name, String.Empty)) Then
              Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
          End If
      End If
  End Sub
  </code></pre>
  
  <p>i have disable ViewstateMac of pages in web config but still i got this error, i know disabling ViewStateMac is not good in security prospective. My application is hosted in web farm on production but not in local environment.</p>