在将用户输入字符串注入模板引擎或简单的JS模板字符串之前,如何清理nodejs中的用户输入字符串



我有一些网页(基本上是名片(,它们的标题是根据用户输入创建的。为此,我计划使用简单的JS模板字符串,而不是一些模板引擎。(我使用express.js/node.js(

response.send(`
<html>
<head>
<title>${user_inputed_title_got_from_DB}</title>
<meta property="og:title" content="${some_more_user_content}" />
</head>
<body>
<script>
window.location.href="/business-card/${user_input_number}";
</script>
</body>
</html>`)

如何避免软性用户注射XSS?

对于普通的HTML标签,这个答案应该足够了:

function escapeHtml(unsafe)
{
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}

但是,需要更加小心地处理脚本标记中的重定向。一种常见的方法是将重定向放在一个属性中,该属性可以通过以下函数进行转义:

<script data-redir="/business-card/${escapeHtml(user_input_number)}">
window.location.href = document.currentScript.dataset.redir;
</script>

最新更新