MVC Anti-XSS方案

/// <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方案的更多相关文章
- ASP.NET MVC 多语言方案
前言: 好多年没写文章了,工作很忙,天天加班, 每天都相信不用多久,就会升职加薪,当上总经理,出任CEO,迎娶白富美,走上人生巅峰,想想还有点小激动~~~~ 直到后来发生了邮箱事件,我竟然忘了给邮箱密 ...
- 360[警告]跨站脚本攻击漏洞/java web利用Filter防止XSS/Spring MVC防止XSS攻击
就以这张图片作为开篇和问题引入吧 <options>问题解决办法请参考上一篇 如何获取360站长邀请码,360网站安全站长邀请码 首先360能够提供一个这样平台去检测还是不错的.但是当体检 ...
- .net mvc 防止 xss 与 CSRF
CSRF(Cross-site request forgery跨站请求伪造,也被称成为“one click attack”或者session riding,通常缩写为CSRF或者XSRF,是一种对网站 ...
- Spring MVC里面xss攻击的预防
关于xss的介绍可以看 Asp.net安全架构之1:xss(跨站脚本)和 腾讯微博的XSS攻击漏洞 网页, 具体我就讲讲Spring MVC里面的预防: 第一种方法,使用Spring MVC web. ...
- 全面解析ASP.NET MVC模块化架构方案
什么叫架构?揭开架构神秘的面纱,无非就是:分层+模块化.任意复杂的架构,你也会发现架构师也就做了这两件事. 本文将会全面的介绍我们团队在模块化设计方面取得的经验.之所以加了“全面”二字,是因为本文的内 ...
- Anti XSS 防跨站脚本攻击库
https://wpl.codeplex.com/ Before understanding Anti-Cross Site Scripting Library (AntiXSS), let us u ...
- MVC模块化开发方案
核心: 主要利用MVC的区域功能,实现项目模块独立开发和调试. 目标: 各个模块以独立MVC应用程序存在,即模块可独立开发和调试. 动态注册各个模块路由. 一:新建解决方案目录结构 如图: 二:Eas ...
- 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 ...
- MVC防止xss攻击 ——Html.AntiForgeryToken的AJAX提交
1.在Html表单里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻击. 2.相应的我们要在Controller中也要加入[ValidateAntiForgeryToken ...
- 【jeecg-mybatis版本】 mybatis+spring mvc 完美整合方案 查询,保存,更新,删除自动生成
Jeecg-Mybatis版本代码生成器演示视频 http://pan.baidu.com/share/link?shareid=243717&uk=2668473880 简要说明 JE ...
随机推荐
- 网页加速特技之 AMP
据统计,40%的人会放弃使用加载时间超过3秒的网站.对于加载慢的页面我也是没耐心等待的,同类型网站那么多,为什么不选择加载速度更快体验更好的呢.为了解决网页加载慢的问题,Google联合数十家技术机构 ...
- [转载] MapReduce工作原理讲解
转载自http://www.aboutyun.com/thread-6723-1-1.html 有时候我们在用,但是却不知道为什么.就像苹果砸到我们头上,这或许已经是很自然的事情了,但是牛顿却发现了地 ...
- 单例模式/ThreadLocal/线程内共享数据
import java.util.Random; public class ThreadDemo3 { public static void main(String[] args) { for(int ...
- Python网络编程篇之select和epoll
1. select 原理 在多路复⽤的模型中, ⽐较常⽤的有select模型和epoll模型. 这两个都是系统接⼝, 由操作系统提供. 当然, Python的select模块进⾏了更⾼级的封装. ⽹络 ...
- unity3d资源打包总结
http://www.manew.com/blog-33734-12973.html unity 打包的时候会把下面几个文件资源打进apk或者ipa包里面 1. Asset下的所有脚本文件 2. As ...
- 关于IDEA无法引入包和类的情况
原因:修改一些包结构后,会出现无法将类引入的情况. 通过清理缓存解决:
- 给负载均衡器添加多IP
看到一个场景,针对web应用的一个需求,需要在负载均衡器设置多个公网ip. 给负载均衡器添加多个公共ip 创建多个虚拟机,同时把他们添加到同一个可用性集中,方便后期部署到负载均衡器. 创建多个公网ip ...
- jQuery中使用$.each()遍历后台响应的json字符串问题
今天在做练习项目的时候,使用$.each()方法遍历后台传过来的json字符串时,chrome浏览器中发现如下问题 Cannot use 'in' operator to search for 'l ...
- Model中设置表单验证方法
Model类里面定义$_validate属性支持的验证因子格式: 格式:array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间). 验证条件: (1)Model::EXISTS_TO_ ...
- 《Linux命令行与shell脚本编程大全》第二十五章 创建与数据库、web及电子邮件相关的脚本
25.1 MySQL数据库 /* 但是我在虚拟机上安装的时候居然不提示输入密码. 这个可以参考http://blog.csdn.net/sinat_21302587/article/details/7 ...