防止jQuery html()中的XSS [英] Prevent XSS in jQuery html()
问题描述
我使用ajax从数据库接收数据,然后使用.html()jQuery函数将其与HTML代码一起添加到网站,如下所示:
I receive data from a database using ajax and then adds it together with HTML code to the website using the .html() jQuery function, like this:
$.ajax({
url: "getDatabaseData.php",
type: "post",
dataType: "json",
success: function(response){
$("#message-div").html(getMessagesHtml(response));
}
});
function getMessagesHtml(messages){
var result = "";
for(var i = 0; i < messages.length; i++){
result +=
"<div>" +
"<p>Name: " + messages[i].name + "</p>" +
"<p>Message: " + messages[i].message + "</p>" +
"</div>";
}
return result;
}
这是从数据库获取并返回数据的getDatabaseData.php:
Here is the getDatabaseData.php that gets and returns the data from the database:
$messages = $CFG_DB->select("SELECT name, message FROM messages");
echo json_encode($messages);
例如,假设消息中包含以下文本:
Imagine for example if message contain the following text:
<script>XSS Attack code goes here</script>
我的问题是:
- 这样做会不会出现XSS问题?
- 万一出现问题,我该如何预防?
我想在这种情况下不可以使用text()而不是html(),因为我还要添加html代码.
I guess that using text() instead of html() is not an option in this case since I also add html code.
没有javascript,当使用PHP打印数据时,我只是在从数据库接收的变量上使用htmlentities来防止XSS,例如htmlentities(messages [i] .name)和htmlentities(messages [i] .message).但是我还没有看到任何类似的javascript.
Without javascript, when printing the data using PHP I just use htmlentities on the variables received from the database to prevent XSS, for example htmlentities(messages[i].name) and htmlentities(messages[i].message). But I have not seen any similar for javascript.
推荐答案
通过用户输入设置文本是最安全的方法.与其创建html字符串,不如创建元素
Setting text with user input is the safest way. Instead of creating html strings, create elements instead
类似的东西:
function getMessagesHtml(messages){
return messages.map(function(o){
var $div = $('<div>');
$div.append($('<p>', {text: "Name: " + o.name}));
$div.append($('<p>', {text: "Message: " + o.message}));
return $div;
});
}
每个注释的替代方法是创建一个清理助手函数,该函数创建一个元素,该元素将输入字符串作为文本传递给该元素并返回该文本
Per comments an alternative is create a sanitizing helper function that creates an element that passes the input string as text to the element and returns that text
function text(str){
return $('<div>',{text:str}).text();
}
这篇关于防止jQuery html()中的XSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!