简体   繁体   中英

AntiForgery cookie in MVC3

I wanted to implement this solution to handle antiforgery in ajax requests. I know there are other solutions but this is the one I like most.

The problem is I have to deal with System.Web.Webpages 1.0 so I cannot make use of AntiForgeryConfig.CookieName in my code.

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

How can I retrieve (programmatically) the cookie name set by the antiforgery system in Mvc3? I suspect the AntiForgery.Validate part will also be a problem but I'll handle that before. Any thoughts?

The actual cookie name always starts from "__RequestVerificationToken" with some suffix. So you can find the cookie like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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