javascript - 防止 html onclick、onmouseout 中的 xss,...用于 SPA

标签 javascript asp.net angularjs asp.net-web-api xss

我正在为我的客户调查系统使用 AngularJSASP.Net Web API 2

我的网站使用 wysiwyg 组件来帮助用户输入他/她的数据。 这是我使用的 wysiwyg 生成的 html:

<h2 style="text-align: center;"><span style="text-decoration: underline;"><strong>Click here</strong></span><strong> to start using the </strong><strong><em>HTML editor online</em></strong></h2>
<p><span style="font-weight: 400;">Please</span><span style="font-weight: 400;"> try out the WYSIWYG HTML editor features found in the kitchen sink above to edit and format your text and images</span></p>
<p><span style="font-weight: 400;">You&rsquo;ll see the content created in the WYSIWYG-HTML editor in source code format on the right.</span><br /><br /></p>
<p>&nbsp;</p>
<p><img onclick="alert('Hello world')" onmouseout="alert('Mouse out')" src="https://icon2.kisspng.com/20180416/ucw/kisspng-tanki-online-video-gaming-clan-world-of-tanks-avat-joker-5ad4b1028d0565.2188790515238883865776.jpg" alt="" width="260" height="260" /></p>

这就是我在 API 上所做的,用于对上面的 html 代码进行编码。

/// Encode submited html content
        /// </summary>
        /// <returns></returns>
        [Route("encode")]
        [HttpPost]
        public IHttpActionResult Encode([FromBody] EncodeViewModel httpContent)
        {
            if (httpContent == null)
            {
                httpContent = new EncodeViewModel();
                Validate(httpContent);
            }

            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var encodedHtmlContent= HttpUtility.HtmlEncode(httpContent.HtmlContent);

            // Save content to database here.
            return Ok(encodedHtmlContent);
        }

当我的前端客户端加载编码的 html 并显示到网站页面时。 我希望当我单击图像时不会显示消息 Hello world鼠标移开

这意味着,我只允许显示文本、图像、视频,但不允许在内容中包含内联代码。

有什么解决办法吗?

谢谢,

最佳答案

确保某些 html 的安全是困难!有一些库可以进行 html XSS 过滤,但它们很大并且仍然很危险。这就是为什么会有像 mobiledoc 这样的东西。一般来说,我建议您不要使用 HTML 作为 WYSIWYG 输出,这样您就不必转义它。而是使用其他东西并从中生成 HTML。然后您就可以确保不会生成危险的 HTML。如果您进行简单的字符串连接,请务必小心。

这就是为什么我们有 BB-Code 或 wiki 标记或 mobiledoc 之类的东西。

关于javascript - 防止 html onclick、onmouseout 中的 xss,...用于 SPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51581808/

相关文章:

javascript - 如何将 VB 变量传递给 JQuery

java - 获取主页的实时库存数据

c# - 如何从 C# ExpandoObject 按名称动态获取属性?

asp.net - 在插入时获取下一个数字,在新的一年重置为 0

javascript - node.js - 将客户端转发到负载最少的集群

c# - 试图在 .NET 应用程序中读取或写入 protected 内存

javascript - 在 AngularJS 中创建循环和过滤器

angularjs - 根据大小响应的自定义磁贴

css - $mdDialog confirm 重新排列 cancel-ok 到 ok-cancel

javascript - 大写两个姓氏之间有破折号