繁体   English   中英

MVC3中的防伪cookie

[英]AntiForgery cookie in MVC3

我想实现此解决方案来处理Ajax请求中的伪造。 我知道还有其他解决方案,但这是我最喜欢的解决方案。

问题是我必须处理System.Web.Webpages 1.0,因此我无法在代码中使用AntiForgeryConfig.CookieName。

public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var request = filterContext.HttpContext.Request;

        //  Only validate POSTs
        if (request.HttpMethod == WebRequestMethods.Http.Post)
        {
            //  Ajax POSTs and normal form posts have to be treated differently when it comes
            //  to validating the AntiForgeryToken
            if (request.IsAjaxRequest())
            {
                string cookieName = AntiForgeryData.GetAntiForgeryTokenName(context.Request.ApplicationPath);
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                var cookieValue = antiForgeryCookie != null
                    ? antiForgeryCookie.Value
                    : null;

                AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
            }
        }
    }

如何检索(以编程方式)由Mvc3中的防伪系统设置的cookie名称? 我怀疑AntiForgery.Validate部分也会有问题,但我会先解决。 有什么想法吗?

实际的cookie名称始终从带有某些后缀的"__RequestVerificationToken"开始。 因此,您可以找到如下所示的Cookie:

private static string FindCookieValueByName(HttpRequestBase request)
{
    return request.Cookies
        .Cast<string>()
        .Where(cn => cn.StartsWith("__RequestVerificationToken", StringComparison.OrdinalIgnoreCase))
        .Select(cn => request.Cookies[cn].Value)
        .FirstOrDefault();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM