【发布时间】:2012-11-06 15:32:46
【问题描述】:
我的一些模型属性由 AllowHtml 属性标记。有什么方法可以自动对这些字段应用 AntiXss 保护(即仅过滤允许的标签)?
【问题讨论】:
标签: asp.net-mvc
我的一些模型属性由 AllowHtml 属性标记。有什么方法可以自动对这些字段应用 AntiXss 保护(即仅过滤允许的标签)?
【问题讨论】:
标签: asp.net-mvc
首先,afaik,没有任何内置功能。 但是 MVC 允许通过自定义 ModelBinders 轻松地做这些事情,你可以定义你的
public class CustomAntiXssAttribute : Attribute { }
并用它装饰您的属性(如果您愿意,甚至可以从AllowHtmlAttribute 继承)。然后使用模型绑定器,您可以添加特定的反 xss 保护:
public class CutstomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Attributes.OfType<CustomAntiXssAttribute>().Any())
{
var valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
var filteredValue = SOME_CUSTOM_FILTER_FUNCTION_HERE(valueResult.AttemptedValue);
propertyDescriptor.SetValue(bindingContext.Model, filteredValue);
}
else // revert to the default behavior.
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
然后在 SOME_CUSTOM_FILTER_FUNCTION_HERE 中,您可以使用 @Yogiraj 建议的内容,或使用正则表达式,甚至应用基于 HtmlAgilityPack 的过滤。
附:不要忘记将ModelBinders.Binders.DefaultBinder = new CutstomModelBinder(); 添加到Application_Start(我忘了:))
【讨论】:
没有自动的方法。您可以做的最接近的是获取 AntiXss Nuget 包。然后你可以在你的控制器中使用它:
Microsoft.Security.Application.Sanitizer.GetSafeHtml("YourHtml");
或
Microsoft.Security.Application.Encoder.HtmlEncode("YourHtml");
如果你使用,你可以使用解码它
Server.HtmlDecode("HtmlEncodedString");
希望这会有所帮助。
【讨论】:
我会用RegularExpression 数据注释验证替换那些AllowHtml 属性。这样做的好处是您可以捕获错误并向用户显示出了什么问题,而前者在全局级别触发错误。
例如
public class MyViewModel
{
[DataType(DataType.MultilineText)]
[RegularExpression(@"^[^\<\>]*$", ErrorMessage = "May not contain <,>")]
public string Text { get; set; }
}
【讨论】:
未经测试的代码,
public class ADefaultModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelMetadata.RequestValidationEnabled)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
value = value.Replace("&", "");// replace existing & from the value
var encodedValue = Microsoft.Security.Application.Encoder.HtmlEncode(value);
bindingContext.ModelMetadata.RequestValidationEnabled = encodedValue.Contains("&"); // Whether AntiXss encoded a char to &..
}
return base.BindModel(controllerContext, bindingContext);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new ADefaultModelBinder();
【讨论】: