通常,在javascript中,使用innerHTML是不是[安全性]问题? [英] in general, in javascript, isn't using innerHTML an [in]security issue?

查看:451
本文介绍了通常,在javascript中,使用innerHTML是不是[安全性]问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有DOM并使用了诸如reactjs之类的新工具,是否应该在javascript程序中使用innerHTML?

使用它很像对SQL注入攻击开放自己,但是这里是跨站点脚本编写等.在使用之前,需要检查并清理所有内容.

在我看来innerHTMLeval()具有相同的安全问题,出于安全考虑应避免使用.

(从美学上讲,也就是我.)

解决方案

是的,innerHTML经常被滥用,并且是客户端HTML注入(DOM-XSS)安全漏洞的非常常见的来源.

通常最好使用对象样式的创建方法,例如createElementtextContent和设置直接DOM属性.与此类似,在jQuery中,更喜欢使用.text().prop()而不是.html()设置变量内容,或者将HTML标记传递给允许它的操作方法.

但是有一些例外情况:

  • 如果您使用的是一种客户端模板语言,可以自动处理HTML换码(例如,带有<%-的lodash模板),则可以安全地将输出写入innerHTML.

  • 如果您将多个同级项附加到单个元素上,并且性能是优先事项(通常的示例是具有大量行的<table>),那么创建HTML标记是值得的,您只需小心手动将所有文本HTML逸出

  • 内容实际上应该是HTML,例如,您具有从Markdown处理的数据.

with the DOM and cool new tools such as reactjs, should innerHTML ever be used in a javascript program?

using it is a lot like opening oneself to an SQL injection attack, but here it's a cross-site scripting etc. everything needs to be examined and scrubbed before it's used.

seems to me innerHTML has the same security issues as eval() and should be avoided for [in]security reasons.

(also aesthetically, but that's just me.)

解决方案

Yes, innerHTML is often misused and a very common source of client-side HTML-injection (DOM-XSS) security holes.

It's usually better to use object-style creation methods, such as createElement, textContent and setting direct DOM properties. Similarly in jQuery, prefer to set variable content using .text() and .prop() rather than .html(), or passing HTML markup to the manipulation methods that allow it.

There are some exceptions though:

  • if you're using a client-side templating language that deals with HTML-escaping for you automatically (eg lodash templates with <%-), it's safe to write the output to innerHTML.

  • if you're appending a lot of siblings to a single element and performance is a priority (the usual example being a <table> with a large number of rows), HTML markup creation can be worth it and you will just have to be careful to HTML-escape all the text manually

  • where the content is actually supposed to be HTML, for example you have data that has been processed from Markdown.

这篇关于通常,在javascript中,使用innerHTML是不是[安全性]问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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