为什么React.js的API警告不要插入原始HTML? [英] Why does React.js' API warn against inserting raw HTML?

查看:99
本文介绍了为什么React.js的API警告不要插入原始HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

教程

但是有一个问题!我们呈现的评论在 浏览器:"<p>This is <em>another</em> comment</p>".我们想要那些标签 实际呈现为HTML.

But there's a problem! Our rendered comments look like this in the browser: "<p>This is <em>another</em> comment</p>". We want those tags to actually render as HTML.

这就是React保护您免受XSS攻击的危险.有办法 围绕它,但是框架警告您不要使用它:

That's React protecting you from an XSS attack. There's a way to get around it but the framework warns you not to use it:

...

<span dangerouslySetInnerHTML={{__html: rawMarkup}} />

这是一个特殊的API,有意使插入原始HTML变得困难,但是对于Showdown,我们将利用此后门.

This is a special API that intentionally makes it difficult to insert raw HTML, but for Showdown we'll take advantage of this backdoor.

记住:通过使用此功能,您依赖Showdown来确保安全.

Remember: by using this feature you're relying on Showdown to be secure.

因此,存在一个用于插入原始HTML的API,但是方法名称和文档均会对其发出警告.使用这个安全吗?例如,我有一个聊天应用程序,它接受Markdown注释并将其转换为HTML字符串. HTML代码段由Markdown转换器在服务器上生成.我相信转换器,但是我不确定用户是否可以通过任何方式精心设计Markdown来利用XSS.我还有什么要确保它安全的事情?

So there exists an API for inserting raw HTML, but the method name and the docs all warn against it. Is it safe to use this? For example, I have a chat app that takes Markdown comments and converts them to HTML strings. The HTML snippets are generated on the server by a Markdown converter. I trust the converter, but I'm not sure if there's any way for a user to carefully craft Markdown to exploit XSS. Is there anything else I should be doing to make sure this is safe?

推荐答案

大多数Markdown处理器(我相信还有Showdown)都允许作者使用内联HTML.例如,用户可以输入:

Most Markdown processors (and I believe Showdown as well) allow the writer to use inline HTML. For example a user might enter:

This is _markdown_ with a <marquee>ghost from the past</marquee>. Or even **worse**:
<script>
  alert("spam");
</script>

这样,您应该有一个标签白名单,并在从markdown转换为html之后删除所有其他标签.只有这样才能使用适当命名的dangerouslySetInnerHTML.

As such, you should have a whitelist of tags and strip all the other tags after converting from markdown to html. Only then use the aptly named dangerouslySetInnerHTML.

请注意,这也是Stackoverflow的功能.上面的Markdown呈现如下(没有让您的脸部发出警报):

Note that this also what Stackoverflow does. The above Markdown renders as follows (without you getting an alert thrown in your face):

这是降价,带有过去的幽灵.或者 甚至更糟:

This is markdown with a ghost from the past. Or even worse:

这篇关于为什么React.js的API警告不要插入原始HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆