设置Page.ViewStateUserKey后反序列化视图状态字符串



我使用自动生成的代码来防止asp.net web应用程序的跨站点伪造攻击,即:

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;

当使用Ajax/Webmethod请求时,我还想在更改数据库之前验证该请求,方法是返回_VIEWSTATE隐藏输入的值。

然而,当我尝试时

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);

洛杉矶。反序列化方法失败,返回:

 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

即单独的UserKey不是编码的视图状态字符串的正确密钥。

请任何人帮助如何反序列化视图状态,在设置ViewStateUserKey属性(即MAC和UserKey的某种组合)后编码。感谢您的想法/专业知识。

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

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

只要Page.ViewStateUserKey已经设置,返回的persister实例也将相应地设置其修饰符。

最新更新