I am using the auto-generated code for preventing cross site forgery attacks with asp.net web applications - ie:
protected const string AntiXsrfTokenKey = "__AntiXsrfToken";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
When using an Ajax/Webmethod request, I would also like to validate the request before altering the database, by posting back the value of the _VIEWSTATE hidden input.
However, when I try
internal static void Validate(string encodedViewstate)
{
var request = HttpContext.Current.Request;
var requestCookie = request.Cookies[AntiXsrfTokenKey];
var antiXsrfTokenValue = requestCookie.Value;
var los = new System.Web.UI.LosFormatter(true, antiXsrfTokenValue);
var xsrfData = los.Deserialize(encodedViewstate);
the los.Deserialize method fails with:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm
ie the UserKey alone is not the correct key for the encoded viewstate string.
Can anyone please help in how to deserialize the viewstate, encoded after setting the ViewStateUserKey property (ie some combination of the MAC and UserKey). Thanks for your thoughts/expertise.
You'll need to use the same PageStatePersister instance that the Page itself uses. Otherwise this check won't work reliably. For example, consider this instance method in your Page's code-behind:
As long as Page.ViewStateUserKey is already set, the returned persister instance will have its modifier also set appropriately.