消毒剂 VS dangerouslySetInnerHtml

Sanitizers VS dangerouslySetInnerHtml

根据一些 React documentation:

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

似乎不​​当使用消毒剂和 innerHTML 可以暴露站点 XSS(跨站点脚本)攻击。

另一方面,根据其他文档(例如Gatsby or sanitizers本身),推荐它们:

The most straightforward way to prevent a XSS attack is to sanitize the innerHTML string before dangerously setting it. Fortunately, there are npm packages that can accomplish this; packages like sanitize-html and DOMPurify.

避免应用程序在 React 中遭受 XSS 攻击同时避免不当使用消毒剂的最佳和最安全的方法是什么?

这两个选项并不矛盾:

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack

强调'improper'。

sanitize the innerHTML string before dangerously setting it

使用已建立的 well-known 库在设置之前对输入进行清理是安全的,因为这不是对 innerHTML 的不当使用。

我认为最好、最安全和最佳的方法,正如评论所说(尤其是 Corey Ward) is to avoid the usage of the dangerouslySetInnerHtml as long as it is possible (so sanitizers too). There are some amazing libraries such as markdown-to-jsx 扩展了 dangerouslySetInnerHtml 的好处(呈现 HTML)而不将 Web 暴露给 XSS 攻击。

如果use-case的唯一解决方案是使用dangerouslySetInnerHtml,那么解决方案必须使用消毒剂,记住它应该是配置为保留样式、类 和其他所需的行为以避免丢失更改。