2

不建议使用允许覆盖string path的前HtmlHelper.AntiForgeryToken方法。如何设置AntiForgeryToken Cookie路径

[ObsoleteAttribute("This method is deprecated. Use the AntiForgeryToken() method instead. To specify a custom domain for the generated cookie, use the <httpCookies> configuration element. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.", 
    true)] 
public MvcHtmlString AntiForgeryToken(
    string salt, 
    string domain, 
    string path 
) 

告诉您使用<httpCookies>。但httpCookies Element没有PATH设置。

这是在这种方法的贬低的疏忽?覆盖这个cookie路径的最佳方法是什么? (手动?)在虚拟应用程序中运行网站不是隐式地将应用程序路径添加到__RequestVeririfcation cookie。

+0

您是否找到解决此问题的解决方案? –

回答

1

综观过时消息:

“此方法已使用AntiForgeryToken()方法,而不是要为生成的cookie指定自定义域,使用配置元件指定自定义数据。被嵌入到令牌中,请使用静态AntiForgeryConfig.AdditionalDataProvider属性。“

它告诉我们,只要伪造令牌被读回,我们就可以验证附加参数。因此,即使我们无法在Cookie中设置路径,我们也可以将路径设置为标记内的属性。为了验证它以后,例如:

public class AdditionalDataProvider : IAntiForgeryAdditionalDataProvider 
{ 
    public string GetAdditionalData(HttpContextBase context) 
    { 
     return AdditionalData(context); 
    } 

    public bool ValidateAdditionalData(HttpContextBase context, string additionalData) 
    { 
     var currentData = AdditionalData(context); 
     return currentData == additionalData; 
    } 

    private static string AdditionalData(HttpContextBase context) 
    { 
     var path = context.Request.ApplicationPath; 
     return path; 
    } 
} 

当asp.net产生,如果您有另一个应用程序将保存当前的路径(或要验证的任何其他唯一值)为应用程序和 令牌运行在不同的路径上,当令牌被发送到该应用程序时(由于缺少cookie路径),它将根据该应用程序的属性验证以前的应用程序属性。如果它是一组不同的属性,它将失败并拒绝请求。

另外,在看的AntiforgeryConfig.cs的代码,如果应用程序在虚拟目录中运行,这将增加该虚拟目录中的cookie的名字默认为:

private static string GetAntiForgeryCookieName() 
{ 
    return GetAntiForgeryCookieName(HttpRuntime.AppDomainAppVirtualPath); 
} 

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

因此,这将是这个样子: _RequestVerificationToken VS _RequestVerificationToken _L2RIdjAz0

含义应用2虽然CA n从App1接收到令牌时,它将无法读取它们,因为它只会始终查找App2验证令牌。

HTH

+0

这很好,除了它仍然不写入cookie上的路径属性。 [见](https://tools.ietf.org/html/rfc6265#section-5.2.4) – felickz