【问题标题】:How to sanitize user input string in nodejs, before injecting it in a template engine or say simple JS template string?如何在 nodejs 中清理用户输入字符串,然后将其注入模板引擎或说简单的 JS 模板字符串?
【发布时间】:2022-02-13 22:15:09
【问题描述】:
我有一些网页(基本上是名片),其标题是根据用户输入创建的。
我打算为此使用简单的 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 注入?
【问题讨论】:
标签:
javascript
node.js
express
xss
【解决方案1】:
对于普通的 HTML 标签,this answer should suffice:
function escapeHtml(unsafe)
{
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
但是,您在脚本标记中的重定向需要更加小心。一种常见的方法是将重定向放在一个属性中,可以使用上述函数对其进行转义:
<script data-redir="/business-card/${escapeHtml(user_input_number)}">
window.location.href = document.currentScript.dataset.redir;
</script>