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 ...
随机推荐
- javaScript函数提升及作用域
代码片段: var a = 1; function foo() { console.log(a); //输出为undefined if (!a) { var a = 2; } alert(a); }; ...
- spring AOP 和自定义注解进行身份验证
一个SSH的项目(springmvc+hibernate),需要提供接口给app使用.首先考虑的就是权限问题,app要遵循极简模式,部分内容无需验证,用过滤器不能解决某些无需验证的方法 所以最终选择用 ...
- C#编写的艺术字类方法
代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing ...
- Unity跨平台C/CPP动态库编译---可靠UDP网络库kcp基于CMake的各平台构建实践
1.为什么需要动态库 a)提供原生代码(native code)的支持,也叫原生插件,但是我实践的是c/cpp跨平台动态库,这里不具体涉及安卓平台java库和ios平台的objectc库构建. b)某 ...
- Python之matplotlib模块安装
numpy 1.下载安装 源代码 http://sourceforge.net/projects/numpy/files/NumPy/ 安装 python2.7 setup.py install 2. ...
- Python待分析的模块
fcntl 文件控制模块 http://docs.python.org/2.7/library/fcntl.html#module-fcntl struct 二进制文本处理模块 http://docs ...
- 用Python写一款属于自己的 简易zip压缩软件 附完成图(适合初学者)
一.软件描述 用Python tkinter模块写一款属于自己的压缩软件.zip文件格式是通用的文档压缩标准,在ziplib模块中,使用ZipFile来操作zip文件,具有功能:zip压缩功能,zip ...
- one 策略模式 strategy
--读书笔记 定义 策略模式--定义算法簇,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客户.(看不懂的话,往下,有人话版/我自己的解释) 相关原则 > 1,变化单独 ...
- 深入浅出多线程——ReentrantLock (二)
深入浅出多线程——ReentrantLock (一)文章中介绍了该类的基本使用,以及在源码的角度分析lock().unlock()方法.这次打算在此基础上介绍另一个极为重要的方法newConditio ...
- 如何在仅主机模式下ping通网路上网
1 主机的控制面板,找到电脑的实际网卡,勾选,并选择VMware Network Adapter VMnet1 找到虚拟网卡VMware Virtual Ethernet Adapter for VM ...