So, the question is simple, even though I'm starting to have doubts if this will get answered...
I have a website, where I wanted to secure my viewstate with the recommended ViewStateUserKey..
In my base page (inherited from Page obviously) I have this code:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (User.Identity.IsAuthenticated)
base.ViewStateUserKey = Session.SessionID;
}
Works good on localhost, however, when I upload it to hosting (shared hosting provided by one of our local providers), it gives the traditional "Validation of viewstate MAC failed" error after I authenticate. If I comment this code out, it works perfectly, so I'm 1000% sure this is the cause.
What's the best approach to perform viewstate security on the shared hosting? I have already set ViewStateMac="Enabled" as well. Is it enough or what is the recommended workaround?
from the moment that is play on local host and not on server then is seems to me that you have some issues with the session, and the sessionID is change/expire fast on your server, faster than the authentication expires.
And for that reason from the time the user see the page, to the post it, the session has expired or change before the Authentication change, so the sessionID is diferent and so you get this error.
Other thinks that you can look is that you have set the machineKey
on web.config.
Update
Compare your code with the Scott you have make a different. Scott use the user name, that is not change at all, and you use the sessionid, that can change as I say.
For me, ether use what Scott suggest, the user name, ether some other value that is not change also, like the cookie of the user for example, that is not change so easy.
So from Scott http://www.hanselman.com/blog/ViewStateUserKeyMakesViewStateMoreTamperresistant.aspx
void Page_Init (Object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
ViewStateUserKey = User.Identity.Name;
}
And this the reason that scott check if the user is Authenticated, because is gets his name. If you go with sessionid, or the cookie of the user, you do not need to check if is authenticated.
Now if you use the cookie to set them on viewstateuserkey, for all users then the one that not permit cookie, and try to make any post it will get error. So think a solution like that to handle them
https://stackoverflow.com/a/2551810/159270