[研究][ASP.NET] 防 XSS 的 HtmlSanitizer ( HTML消毒劑)
2021-09-24
2022-01-03 修訂
2022-06-09 補 mailto
在資料填寫畫面,不管是 TextBox 填寫純文字,或 ckeditor 填寫 HTML內容,要考慮 跨網站指令碼(英語:Cross-site scripting,通常簡稱為:XSS)的過濾處理。
NuGet
https://www.nuget.org/packages/HtmlSanitizer/
官方網站
https://github.com/mganss/HtmlSanitizer
WebForm.aspx.cs
public static string MyAntiXssFilter(object inputObject) { string inputStr = ""; if (inputObject != null) { inputStr = inputObject.ToString(); } var sanitizer = new HtmlSanitizer(); sanitizer.AllowedAttributes.Add("class"); sanitizer.AllowedAttributes.Add("id"); var sanitized = sanitizer.Sanitize(inputStr); return sanitized; } |
WebForm.aspx
e.NewValues["內容"] = Common.MyAntiXssFilter(e.NewValues["內容"]); |
若要把每一項都過濾
foreach (DictionaryEntry entry in e.NewValues) { e.NewValues[entry.Key] = Common.MyAntiXssFilter(entry.Value); |
2022-01-03
注意,MyAntiXssFilter 參數若為網址,& 會變成 & ,無法傳1個以上參數,改成
public static string MyAntiXssFilter(object inputObject) { string inputStr = ""; if (inputObject != null) { inputStr = inputObject.ToString(); } var sanitizer = new HtmlSanitizer(); sanitizer.AllowedAttributes.Add("class"); sanitizer.AllowedAttributes.Add("id"); sanitizer.AllowedSchemes.Add("mailto"); // 允許 <a href="mailto:" //sanitizer.AllowedAttributes.Add("&"); // 沒用; 若處理網址, & 會變成 & var sanitized = sanitizer.Sanitize(inputStr); sanitized = sanitized.Replace("&", "&"); return sanitized; } |
(完)
沒有留言:
張貼留言