简体   繁体   中英

React: dangerouslySetInnerHTML

I've question about dangerouslySetInnerHTML, is it dangerous to use it, when the html comes from my api or there is no difference and maybe attacked anyway? Thanks

When the HTML comes from any API is when it's most dangerous to use dangerouslySetInnerHTML .

This is covered in the docs :

In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

Essentially, the issue is that if your server doesn't properly sanitise user input, you open your site up to attacks that React protects you from by default. For example, lets say you allow users to write comments on your website, and your API sends back those comments in HTML. If a user writes a comment like eg

my comment <img src="./404" onerror="alert('test')" />

then eg that JavaScript code might be executed whenever someone else views that comment, unless you remember to protect against that when processing the comments.


I'd recommend returning your data from your API in a different format (eg JSON), and then processing it into React elements on the frontend.

DangerouslySetInnerHTML

Yes, there's potential concern. Although, you'll gain some extra performance, since react doesn't compare the dangerouslySetInnerHTML field with Virtual DOM.

HOW EXACTLTY IT'S DANGEROUS?

If user add some malicious code into the comments / other inputs and this data renders on the dangerouslySetInnerHTML field via API, your application deal with XSS Attack ([https://owasp.org/www-community/attacks/xss/][1]).

HOW CAN POTENTIAL XSS BE PREVENTED?

Based on the best practices, it's best to sanitize the dangerouslySetInnerHTML element with some external modules like: DOMPurify (https://github.com/cure53/DOMPurify). It will remove/filter out the potentially malicious code from the HTML and prevent XSS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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