Sanitizers VS dangerouslySetInnerHtml

余生长醉 提交于 2021-01-29 20:50:48

问题


According to some 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.

It seems that improper usage of the sanitizers and the innerHTML can expose the site XSS (Cross-Site Scripting) attacks.

On the other hand, according to other documentation (such as Gatsby or sanitizers itself), they are recommended:

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.

What's the best and safest approach to avoid exposing an application to XSS attacks in React while also avoiding improper usage of sanitizers?


回答1:


The two options are not in contrast with each other:

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

Emphasis on 'improper'.

sanitize the innerHTML string before dangerously setting it

Using an established and well known library to sanitize the input before setting it is safe, because it is not an improper use of innerHTML.




回答2:


I think the best, safest, and optimal approach, as it has been said through comments (especially by 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 that extends the benefits of dangerouslySetInnerHtml (rendering HTML) without exposing the web to XSS attacks.

If the only solution for the use-case is to usedangerouslySetInnerHtml, then the solution must be using sanitizers, keeping in mind that it should be configured to keep styles, classes, and other desired behavior to avoid losing changes.



来源:https://stackoverflow.com/questions/64261021/sanitizers-vs-dangerouslysetinnerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!