【问题标题】:MVC4 AntiForgery token cookie name is appended with random stringMVC4 AntiForgery 令牌 cookie 名称附加随机字符串
【发布时间】:2019-11-19 14:28:02
【问题描述】:

我遇到了 MVC4 的问题

@Html.AntiForgeryToken()

html 助手。在我的开发机器上,当我运行项目时,在检查标头(使用 Fiddler)时,返回的令牌名称是

__RequestVerificationToken

但当部署到 IIS 7.5 版(Windows 2008 R2)时,令牌名称如下所示:

__RequestVerificationToken_L2V6b3JkZXI1

这在哪里发生了变化?是不是因为我的应用程序没有部署到 IIS 的“根文件夹”?例如。我的应用程序部署到

"http://myserver/myapp" instead of "http://myserver"

【问题讨论】:

    标签: asp.net-mvc-4 antiforgerytoken


    【解决方案1】:

    看了源码找到了答案:

    http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.WebPages/Helpers/AntiForgeryConfig.cs
    

    是的,因为我的应用程序被部署到一个路径,下面的代码附加了该路径的编码等效项......希望这个发现可以为您省去麻烦。

            // If the app path is provided, we're generating a cookie name rather than a field name, and the cookie names should
        // be unique so that a development server cookie and an IIS cookie - both running on localhost - don't stomp on
        // each other.
        internal static string GetAntiForgeryCookieName(string appPath)
        {
            if (String.IsNullOrEmpty(appPath) || appPath == "/")
            {
                return AntiForgeryTokenFieldName;
            }
            else
            {
                return AntiForgeryTokenFieldName + "_" + HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(appPath));
            }
        }
    

    【讨论】:

    • 我们能做些什么来解决这个问题。抱歉,我正在将 cmets 添加到一个非常旧的线程中
    • 您能否具体说明您为解决此问题所采取的步骤
    【解决方案2】:

    使用 AntiForgeryConfig 类很容易解决这个问题。请参阅下面的参考。

    https://docs.microsoft.com/en-us/dotnet/api/system.web.helpers.antiforgeryconfig?view=aspnet-webpages-3.2

    Namespace:System.Web.Helpers
    

    您需要在 Global.asax 文件的 Application_Start() 事件下添加以下代码。

    if (AntiForgeryConfig.CookieName.Contains("__RequestVerificationToken"))
                {
                    AntiForgeryConfig.CookieName = "__RequestVerificationToken";
                } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-15
      • 2018-03-28
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多