0

I fix Cross-Site Request Forgery (CSRF). In OnInit method of masterpage:

if (requestCookie != null && Utility.GuidTryParse(requestCookie.Value, out requestCookieGuidValue))
{
    _antiXsrfTokenValue = requestCookie.Value;
    Page.ViewStateUserKey = _antiXsrfTokenValue;
}
Page.PreLoad += master_Page_PreLoad;

In master_Page_PreLoad I validate

        if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
        {
            logCSRF.Info("Error CSRF " + CurrentSession.CurrentUser.user_id);
            Response.Redirect(Constants.DefaultPage.LoginPage);
        }

After validate I reset antiXsrfTokenValue and value of cookie:

 _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
 Response.Cookies[AntiXsrfTokenKey].Value = _antiXsrfTokenValue;

Exception thow "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."

Why has this exption?Resolve?

Thanks for help me!

Chip
  • 1
  • 1
  • Why do you reset the token after successful validation? The tokens are intended to be long-lived. – Levi Dec 24 '13 at 15:45
  • I want to change token value for each action. – Chip Dec 25 '13 at 02:30
  • but why? What problem exactly are you trying to solve? As I mentioned earlier - these tokens are intended to be long-lived, so this might not be the best way to achieve your desired goal. If you tell us what your overall scenario is we might be able to suggest a more appropriate course of action. – Levi Dec 25 '13 at 04:14

2 Answers2

0

Allow me to elaborate,

When you deploy an asp.net web app into an environment with multiple servers, each servers machine.config or web.config must specify the same key used for encrypting the view state. The view state is encrypted for security reasons and each machine.config on each web server will have a different key so they must all be the same. Best way is to add a machineKey element into each of the web server's web.config and define the same keys and algorithm. The machineKey goes under the System.web node.

I found a couple of resources that may explain it or answer it a bit better that myself.

Validation of viewstate MAC failed.Application hosted by a Web Farm, ensure configuration

asp.net

Community
  • 1
  • 1
Cody Hicks
  • 420
  • 9
  • 24
-1

try to add this string in section of your web.config file :

<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />
Cody Hicks
  • 420
  • 9
  • 24