简体   繁体   English

我如何安全地从 React 组件渲染 Markdown?

[英]How do I SAFELY render Markdown from a React component?

I want to display markdown in my ReactJS app, but its important that it's done safely.我想在我的 ReactJS 应用程序中显示降价,但它的安全完成很重要。 The markdown files I will be displaying are untrusted public content.我将显示的降价文件是不受信任的公共内容。

I've seen various solutions and they all use dangerouslySetInnerHTML.我见过各种解决方案,它们都使用危险的SetInnerHTML。

I can't help thinking that this might be, well, dangerous.我不禁想到这可能很危险。

Anyone have any ideas?任何人有任何想法?

thanks谢谢

They gave dangerouslySetInnerHTML a scary name very deliberately , to make sure people would think very carefully about whether they needed to use it/whether they were using it correctly. 他们非常刻意地给dangerouslySetInnerHTML的SetInnerHTML起了一个可怕的名字,以确保人们会非常仔细地考虑他们是否需要使用它/他们是否正确使用它。 Seeing as you're asking this question, clearly it's done that job pretty well!看到你问这个问题,显然它做得很好! But Markdown rendering is in fact one instance where it's necessary.但 Markdown 渲染实际上是一种必要的情况。

Basically, what it comes down to is: dangerouslySetInnerHTML is only dangerous when you don't make sure the stuff you're putting into it is safe beforehand.基本上,它归结为:只有当您事先没有确保放入其中的内容是安全的时, dangerouslySetInnerHTML才是危险的。 Be careful, but don't be scared off by it!要小心,但不要被它吓跑!

EDIT: As mentioned by Waylan in the comments, the example I gave was pretty naive and didn't take into account other ways XSS attacks can be achieved through Markdown .编辑:正如 Waylan 在评论中提到的,我给出的例子非常幼稚,没有考虑到XSS 攻击可以通过 Markdown 实现的其他方式 Most likely you're going to want to run the output through a sanitizer instead of/as well as the input, otherwise it's very possible to generate malicious HTML without doing something as straightforward as just embedding a script tag.您很可能希望通过 sanitizer 而不是/以及输入来运行输出,否则很可能会生成恶意 HTML,而无需执行像嵌入script标签那样简单的操作。 The main point of my answer remains the same though;不过,我的回答的要点保持不变; dangerouslySetInnerHTML is only as dangerous as what you put into it. dangerouslySetInnerHTML只和你放入的东西一样危险。 Do your research, make sure the input is safe, and you'll be fine.做你的研究,确保输入是安全的,你会没事的。

If the input is not trusted (and you can't do anything about it) the library should sanitize the input properly before displaying it.如果输入不受信任(并且您对此无能为力),则库应在显示之前正确清理输入。

I have found two libraries that seem to do that:我发现了两个似乎这样做的库:

  • react-markdown反应降价

    Just make sure that escapeHtml option is set to true .只需确保escapeHtml选项设置为true To test, set "HTML mode" to "Escape" on demo page .要进行测试,请在演示页面上将“HTML 模式”设置为“Escape”。

  • remarkable了不起

    Didn't test it, and safety is not "an explicitly stated goal of the project".没有对其进行测试,并且安全性不是“该项目明确规定的目标”。 The information is from 2014 though, so that might have changed (no info in README).该信息来自 2014 年,因此可能已更改(自述文件中没有信息)。 YMMV.天啊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM