0

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.

4

1 回答 1

1

您需要使用 Page 本身使用的相同 PageStatePersister 实例。否则,此检查将无法可靠地工作。例如,在您的 Page 的代码隐藏中考虑这个实例方法:

private void CheckCsrfToken() {
    var persister = this.PageStatePersister;
    persister.Load();
    if (persister.ViewState == null) {
        throw new Exception("Validation failed.");
    }
}

只要 Page.ViewStateUserKey 已经设置,返回的持久化实例也将适当地设置其修饰符。

于 2013-09-03T19:40:52.233 回答