如何设置AntiForgeryToken Cookie路径 [英] How to set the AntiForgeryToken cookie path
本文介绍了如何设置AntiForgeryToken Cookie路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不推荐使用前一种HtmlHelper.AntiForgeryToken方法,该方法允许重写string path
。
[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没有路径设置。
这是不推荐使用此方法时的疏忽吗?覆盖此Cookie路径的最佳方式是什么?(手动?)在虚拟应用程序中运行网站并不是将应用程序路径隐式添加到__RequestVeriiff Cookie。
推荐答案
正在查看弃用消息:
"此方法已弃用。请改用AntiForgeryToken()方法。若要为生成的Cookie指定自定义域,请使用Configuration元素。若要指定要嵌入到令牌中的自定义数据,请使用静态的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_L2RIdjAz0
意味着App2虽然可以从App1接收令牌,但将无法读取它们,因为它将始终只查找App2验证令牌。
HTH
这篇关于如何设置AntiForgeryToken Cookie路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文