我设法使用 NuGet 中的 HtmlSanitizer 解决了这个问题:
https://github.com/mganss/HtmlSanitizer
根据 OWASP 基金会的建议(我需要的好建议):
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.236_-_Sanitize_HTML_Markup_with_a_Library_Designed_for_the_Job
首先,添加 NuGet 包:
> Install-Package HtmlSanitizer
然后我创建了一个扩展方法来简化事情:
using Ganss.XSS;
...
public static string RemoveHtmlXss(this string htmlIn, string baseUrl = null)
{
if (htmlIn == null) return null;
var sanitizer = new HtmlSanitizer();
return sanitizer.Sanitize(htmlIn, baseUrl);
}
然后,当 HTML 发布时,我在控制器内进行验证:
var cleanHtml = model.DodgyHtml.RemoveHtmlXss();
为了完整起见,每次将其呈现到页面时都要进行清理,尤其是在使用 Html.Raw() 时:
<div>@Html.Raw(Model.NotSoSureHtml.RemoveHtmlXss())</div>