Asp.net防御XSS攻击组件库

一、AntiXss

翻看mvc4高级编程,偶看到作者强烈推荐使用AntiXss防御XSS攻击,收集资料看下。

目前类库已融入到.netframework中,类库主页不再更新。

使用方法:使用Nuget,搜索AntiXss

在项目中添加命名空间引用:using Microsoft.Security.Application;

 示例代码:

 string xssstr="<script>alert(0);</script>,;<insert into table";
            string encodedstr= Encoder.HtmlEncode(xssstr, false);
            
            string safestr = Sanitizer.GetSafeHtml(xssstr);
            string safestrfrag = Sanitizer.GetSafeHtml(xssstr);
            encodedstr = Encoder.HtmlEncode(xssstr, false);
View Code

代码运行后,会过滤敏感字符进行转义操作。

使用Sanitizer.GetSafeHtml()会得到过滤过敏感字符的html字符串结果。

 参考资料:

  类库官网

  博客园榨菜小生文章

  csdnVinoYang专栏文章

二、HtmlSanitizer

  VS中使用Nuget控制台安装。

  

  HtmlSanitizer依赖AngleShart库

       public ISet<string> AllowedAttributes { get; }
        public ISet<string> AllowedCssProperties { get; }
        public ISet<string> AllowedSchemes { get; }
        public ISet<string> AllowedTags { get; } 

  通过上述属性可以查看Allowed标签信息。

  HtmlSanitizer可以添加白名单到标签中,类库简单使用示例如下:

  

            //初始化对象
            HtmlSanitizer htmlSanitizer = new HtmlSanitizer();          
            StringBuilder alltag = new StringBuilder();
            foreach (var item in htmlSanitizer.AllowedTags)
            {
                alltag.Append(item + "\r\n");
            }

            //获得AllowedTags
            string allTagsstr = alltag.ToString();

            //过滤操作
            string filterstr = htmlSanitizer.Sanitize(xssstr);
            //添加script到白名单中
            htmlSanitizer.AllowedTags.Add("script");
            //查看过滤后的结果
            filterstr = htmlSanitizer.Sanitize(xssstr);

  HtmlSanitizer以标签为基础单进行过滤,上例中script设置白名单后alert不会被过滤。

 

转载于:https://www.cnblogs.com/bro-ma/p/6777800.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值