1:Form提交模式
在使用Form提交时,MVC框架提供了一个默认的机制。如果数据中含有恶意字,则会自动转向出错页面。
 

2:Ajax+JSON提交模式。
MVC框架未提供对于Json数据的AntiXSS支持,所以必须自行实现。
 
Step1:定义一个Attribute[AllowHtml],如果有这个标记,则说明该属性允许Html,不需要验证。
/// <summary>
/// 用于标记某个属性是否允许html字符
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class AllowHtmlAttribute : Attribute
{ }

Step2:元数据解析的时候,动态设定标记为AllowHtml的属性不激发验证。

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{ public CustomModelMetadataProvider()
{
} protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (containerType == null || propertyName == null)
return metadata; foreach (Attribute attr in attributes)
{
if (attr is AllowHtmlAttribute)
{
metadata.RequestValidationEnabled = false;
break;
}
}
}
}

Step3:实现自定义ModerBinder,拦截所有的json数据,进行anti-xss验证。

/// <summary>
/// 检测Json数据中含有恶意字符,抛出HttpRequestValidationException
/// </summary>
public class AntiXssModelBinder : DefaultModelBinder
{
protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
if (controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
int index; if (controllerContext.Controller.ValidateRequest
&& bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
{
if (value is string)
{
if (AntiXssStringHelper.IsDangerousString(value.ToString(), out index))
{
throw new HttpRequestValidationException("Dangerous Input Detected");
}
}
else if (value is IEnumerable)
{
// 字符串数组或者集合,或者Dictionary<string, string>
// Dictionary的Key, Value会ToString后一起验证
foreach (object obj in value as IEnumerable)
{
if (obj != null)
{
if (AntiXssStringHelper.IsDangerousString(obj.ToString(), out index))
{
throw new HttpRequestValidationException("Dangerous Input Detected");
}
}
}
}
}
} return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
}
} /// <summary>
/// 检测绑定的单值字符串是否包含恶意字符
/// </summary>
public class AntiXssRawModelBinder : StringTrimModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = base.BindModel(controllerContext, bindingContext);
if (value is string)
{
var result = (value as string).Trim();
int index;
if (AntiXssStringHelper.IsDangerousString(value.ToString(), out index))
{
throw new HttpRequestValidationException("Dangerous Input Detected");
}
} return value;
}
}
}

Step4:在Web站点启动的时候,配置MVC框架

RouteTableRegister.RegisterRoutes(_routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ModelMetadataProviders.Current = new CustomModelMetadataProvider();
ModelBinders.Binders.DefaultBinder = new AntiXssModelBinder();

举例:

[Required]
[AllowHtml]
public string UserName{get;set;}
[Required]
public string Password{get;set;}
注意:这时通过JSON传过来的数据Password就会报错,而UserName则不会。

如果Ajax传入的JSON是封装好的对象,最好也要经过封装,以下为例:

 public ActionResult Login(LoginModel model,[ModelBinder(typeof(AntiXssRawModelBinder))])
{
} //AntiXssRawModelBinder核心代码
/// <summary>
/// 检测绑定的单值字符串是否包含恶意字符
/// </summary>
public class AntiXssRawModelBinder : StringTrimModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = base.BindModel(controllerContext, bindingContext);
if (value is string)
{
var result = (value as string).Trim();
int index;
if (AntiXssStringHelper.IsDangerousString(value.ToString(), out index))
{
throw new HttpRequestValidationException("Dangerous Input Detected");
}
} return value;
}
}

如果某些参数需要支持部分HTML代码,可以采取先将该参数设置为[AllowHTML],值传到Action时,再进行手动过滤,或者 使用AntiXSS库进行编码(微软提供的AntiXSSLibrary类库)。

MVC Anti-XSS方案的更多相关文章

  1. ASP.NET MVC 多语言方案

    前言: 好多年没写文章了,工作很忙,天天加班, 每天都相信不用多久,就会升职加薪,当上总经理,出任CEO,迎娶白富美,走上人生巅峰,想想还有点小激动~~~~ 直到后来发生了邮箱事件,我竟然忘了给邮箱密 ...

  2. 360[警告]跨站脚本攻击漏洞/java web利用Filter防止XSS/Spring MVC防止XSS攻击

    就以这张图片作为开篇和问题引入吧 <options>问题解决办法请参考上一篇 如何获取360站长邀请码,360网站安全站长邀请码 首先360能够提供一个这样平台去检测还是不错的.但是当体检 ...

  3. .net mvc 防止 xss 与 CSRF

    CSRF(Cross-site request forgery跨站请求伪造,也被称成为“one click attack”或者session riding,通常缩写为CSRF或者XSRF,是一种对网站 ...

  4. Spring MVC里面xss攻击的预防

    关于xss的介绍可以看 Asp.net安全架构之1:xss(跨站脚本)和 腾讯微博的XSS攻击漏洞 网页, 具体我就讲讲Spring MVC里面的预防: 第一种方法,使用Spring MVC web. ...

  5. 全面解析ASP.NET MVC模块化架构方案

    什么叫架构?揭开架构神秘的面纱,无非就是:分层+模块化.任意复杂的架构,你也会发现架构师也就做了这两件事. 本文将会全面的介绍我们团队在模块化设计方面取得的经验.之所以加了“全面”二字,是因为本文的内 ...

  6. Anti XSS 防跨站脚本攻击库

    https://wpl.codeplex.com/ Before understanding Anti-Cross Site Scripting Library (AntiXSS), let us u ...

  7. MVC模块化开发方案

    核心: 主要利用MVC的区域功能,实现项目模块独立开发和调试. 目标: 各个模块以独立MVC应用程序存在,即模块可独立开发和调试. 动态注册各个模块路由. 一:新建解决方案目录结构 如图: 二:Eas ...

  8. NAXSI means Nginx Anti XSS & SQL Injection. NAXSI is an open-source, high performance, low rules maintenance WAF for NGINX

    nbs-system/naxsi: NAXSI is an open-source, high performance, low rules maintenance WAF for NGINXhttp ...

  9. MVC防止xss攻击 ——Html.AntiForgeryToken的AJAX提交

    1.在Html表单里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻击. 2.相应的我们要在Controller中也要加入[ValidateAntiForgeryToken ...

  10. 【jeecg-mybatis版本】 mybatis+spring mvc 完美整合方案 查询,保存,更新,删除自动生成

    Jeecg-Mybatis版本代码生成器演示视频 http://pan.baidu.com/share/link?shareid=243717&uk=2668473880   简要说明  JE ...

随机推荐

  1. WPF 完美截图 <一>

    最近比较懒,一直没继续,此处省略一万字,下面开始正题. 简单介绍下截图的思路: 核心是利用 public CroppedBitmap(BitmapSource source, Int32Rect so ...

  2. (二)SVN的安装

    1,首先下载SVN的服务端和客户端地址如下http://subversion.apache.org/packages.html.进入网址后滚动到浏览器最底部. (因为我的系统是Windows所以我选择 ...

  3. protobuf/android 交叉编译笔记

    protobuf 交叉编译笔记 目标是使用 android ndk 的工具链编译出 android armeabi-v7a 可用的 protobuf 库. 交叉编译环境配置 windows 平台 下载 ...

  4. node笔记-node的好基友monggoDB

    mongoDB--非关系型数据库的佼佼者 mongodb是一个基于分布式文件存储的数据库,由c++语言编写. 特点:高性能.易部署.易使用. 下载地址:http://www.mongodb.org/d ...

  5. 【机器学习】DNN训练中的问题与方法

    感谢中国人民大学的胡鹤老师,人工智能课程讲的很有深度,与时俱进 由于深度神经网络(DNN)层数很多,每次训练都是逐层由后至前传递.传递项<1,梯度可能变得非常小趋于0,以此来训练网络几乎不会有什 ...

  6. 为Spark Application指定不同的JDK版本

    随着企业内部业务系统越来越多,基于JVM的服务,通常情况线上环境可能会有多套JDK跑不同的服务.大家都知道基于高版本的Java规范编写的服务跑在低版本的JVM上会出现:java.lang.Unsupp ...

  7. docker-compose v3版本命令详解参考

    参考和指南 这些主题描述了Compose文件格式的第3版.这是最新的版本. Compose and Docker 兼容性矩阵 有几个版本的Compose文件格式 - 1,2,2.x和3.x.下表是快速 ...

  8. buttongroup中content一次性加载的解决方法

    buttongroup一次性加载所有内容的解决方法 如下图所示: 第一步: 设置windowcontainer的autoLoad属性为false(默认情况下autoLoad属性为true,所以会加载所 ...

  9. 企业级缓存系统varnish应用

    场景 随着公司业务快速发展,公司的电子商务平台已经聚集了很多的忠实粉丝,公司也拿到了投资,这时老板想通过一场类似双十一的活动,进行一场大的促销,届时会有非常多的粉丝访问网站,你的总监与市场部门开完会后 ...

  10. P1373 小a和uim之大逃离

    转自:http://www.cnblogs.com/CtsNevermore/p/6028138.html 题目背景 小a和uim来到雨林中探险.突然一阵北风吹来,一片乌云从北部天边急涌过来,还伴着一 ...