【问题标题】:AntiForgeryConfig.CookieName inconsistent with HttpContext.Request.Cookies - why?AntiForgeryConfig.CookieName 与 HttpContext.Request.Cookies 不一致 - 为什么?
【发布时间】:2012-10-12 11:09:32
【问题描述】:

我们有一个用 ASP.NET MVC 3 编写的应用程序,它使用 @Html.AntiForgeryToken()

我们想要验证自定义属性中的令牌(无需指定默认属性[ValidateAntiForgeryToken])。这应该很简单,但我发现了一个有趣的不一致之处。

  1. 以下所有代码都在以下方法中运行:

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {  
        public void OnAuthorization(AuthorizationContext filterContext)
        {
        ...
    
  2. AntiForgeryConfig.CookieName 的值为__RequestVerificationToken。这似乎有道理。

  3. filterContext.HttpContext.Request.Cookies 包含 1 个 cookie - 但它的名称是 __RequestVerificationToken_Lw__

问题:这两个不应该是一样的,所以我可以使用下面的sn-p来获取cookie吗?

var cookie = filterContext.HttpContext.Request.Cookies[AntiForgeryConfig.CookieName];

【问题讨论】:

    标签: asp.net-mvc-3 antiforgerytoken


    【解决方案1】:

    在 MVC 3 和 MVC 4 之间更改了默认 cookie 名称。在 MVC 3 中,默认 cookie 名称包含“Lw”和接近末尾的额外下划线。您能否确认 cookie 是由 MVC 4 应用程序而不是 MVC 3 应用程序生成的?

    【讨论】:

    • 我假设它是生成 cookie 的 @Html.AntiForgeryToken() - 在这种情况下,我确信它来自 System.Web.Mvc,版本 3.0.0.0 ([assembly: AssemblyFileVersion (“3.0.20105.0”)])。 AFAIR,这正是 ASP.NET MVC 3 附带的版本 - MVC 4 的相应库是 System.Web.Mvc,版本 4.0.0.0 ([assembly: AssemblyFileVersion("4.0.20710.0")]) 而这样的版本不是在项目中引用。
    • 我问的原因是 AntiForgeryConfig API 直到 MVC 4 才被添加,这个问题让你看起来好像是使用 MVC 3 生成令牌但是 使用它使用 MVC 4,例如有两种不同的应用程序在起作用。
    • 其实...你是对的。引用库存在不一致:来自 MVC3 的 System.Web.Mvc 和来自 MVC4 的 System.Web.WebPages。由于 WebPages 具有不同的版本控制模式(1.0 -> 2.0,而不是 3.0 -> 4.0),因此并不容易注意到这一点。非常感谢,这是一个很好的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多