參考地址:http://www.javashuo.com/article/p-ncfxkizn-dz.htmlhtml
測試項目:MVCDemo前端
1、XSS漏洞定義web
XSS攻擊全稱跨站腳本攻擊,它容許惡意web用戶將代碼(如:html代碼)植入到頁面上,當訪問到該頁面時,嵌入到頁面的html代碼會自動執行,從而達到惡意攻擊的目的。ide
2、解決方案測試
1.新創建一個XSSHelper幫助類spa
1 public static class XSSHelper 2 { 3 /// <summary> 4 /// XSS過濾 5 /// </summary> 6 /// <param name="html">html代碼</param> 7 /// <returns>過濾結果</returns> 8 public static string XssFilter(string html) 9 { 10 string str = HtmlFilter(html); 11 return str; 12 } 13 14 /// <summary> 15 /// 過濾HTML標記 16 /// </summary> 17 /// <param name="Htmlstring"></param> 18 /// <returns></returns> 19 public static string HtmlFilter(string Htmlstring) 20 { 21 string result = System.Web.HttpUtility.HtmlEncode(Htmlstring); 22 return result; 23 } 24 }
2.再創建一個XSSFilterAttribute過濾類code
1 /// <summary> 2 /// XSS 過濾器 3 /// </summary> 4 public class XSSFilterAttribute : ActionFilterAttribute 5 { 6 /// <summary> 7 /// OnActionExecuting 8 /// </summary> 9 /// <param name="context"></param> 10 public override void OnActionExecuting(ActionExecutingContext context) 11 { 12 //獲取參數集合 13 var ps = context.ActionDescriptor.GetParameters(); 14 if (ps.Count() == 0) 15 { 16 return; 17 } 18 //遍歷參數集合 19 foreach (var p in ps) 20 { 21 if (context.ActionParameters[p.ParameterName] != null) 22 { 23 //當參數是str 24 if (p.ParameterType.Equals(typeof(string))) 25 { 26 context.ActionParameters[p.ParameterName] = XSSHelper.XssFilter(context.ActionParameters[p.ParameterName].ToString()); 27 } 28 else if (p.ParameterType.Equals(typeof(Int64))) 29 { 30 31 } 32 else if (p.ParameterType.Equals(typeof(Int32))) 33 { 34 35 } 36 37 else if (p.ParameterType.IsClass)//當參數是一個實體 38 { 39 PostModelFieldFilter(p.ParameterType, context.ActionParameters[p.ParameterName]); 40 } 41 } 42 43 } 44 } 45 /// <summary> 46 /// 遍歷實體的字符串屬性 47 /// </summary> 48 /// <param name="type">數據類型</param> 49 /// <param name="obj">對象</param> 50 /// <returns></returns> 51 private object PostModelFieldFilter(Type type, object obj) 52 { 53 if (obj != null) 54 { 55 foreach (var item in type.GetProperties()) 56 { 57 if (item.GetValue(obj) != null) 58 { 59 //當參數是str 60 if (item.PropertyType.Equals(typeof(string))) 61 { 62 string value = item.GetValue(obj).ToString(); 63 item.SetValue(obj, XSSHelper.XssFilter(value)); 64 } 65 else if (item.PropertyType.Equals(typeof(Int64))) 66 { 67 68 } 69 else if (item.PropertyType.Equals(typeof(Int32))) 70 { 71 72 } 73 else if (item.PropertyType.Equals(typeof(Int16))) 74 { 75 76 } 77 else if (item.PropertyType.IsClass)//當參數是一個實體 78 { 79 // item.SetValue(obj, PostModelFieldFilter(item.PropertyType, item.GetValue(obj))); 80 } 81 } 82 83 } 84 } 85 return obj; 86 } 87 }
3.在控制器上加上該屬性,就可對傳遞過來的參數數值進行過濾(記得要引入對應的命名空間)htm
說明:爲何要加入[ValidateInput(false)],由於用戶若是加入相似<script>的話,直接就報錯了,界面不友好,因此就修改成後臺對輸入的內容進行過濾處理。若是壓根不但願用戶輸入相似的字符,須要也在前端進行一下驗證就能夠了。對象