views:

331

answers:

3

I have the following in my BasePage class which all my ASPX pages derive from:

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

I also have a machineKey set in Web.config. I don't think this error is because of a web farm because this happens on my dev machine too.

My host has now upgraded to .NET 3.5 SP1. After this update, everytime I compile with the ViewStateUserKey setting above, I constantly get the "Validation of viewstate MAC failed" error on every postback.

What am I doing wrong here? Is this setting even necessary anymore with the latest framework update?

+1  A: 

Can you turn off ViewState MAC encoding with the EnableViewStateMac @Page attribute?

David Andres
Yes, it works if I do this. I'd rather remove the ViewStateUserKey setting if it's of no use...
Druid
Well, if getting rid of the ViewStateUserKey works and you don't need it...
David Andres
True, but it seems setting this helps against one click (CSRF) attacks...
Druid
...then you do need it!
David Andres
+1  A: 

I fixed it for now by changing the code to:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    if (User.Identity.IsAuthenticated)
        ViewStateUserKey = User.Identity.Name;
}
Druid
Awesome, give yourself a check for the correct answer.
David Andres
A: 

OK - Im a year late to the conversation - but how is this the correct answer? This applies only in the case of authenticated users and using the ViewStateUserKey as the username is a lot easier to guess than a session id GUID.

BTW if you want to 'fix' the code up top, use the Session ID, however you must set a session variable in order for the session id to stop from changing every time. Ex. Session["Anything"] = DateTime.Now

ViewStateUserKey = Session.SessionID;

This of course is assuming you are going to use sessions, otherwise you need some other key to use such as the username or any other guid kept in a cookie.

Adam Tuliper