最佳答案
有没有可能像 PHP 使用预备语句那样防止 Node.js 中的 SQL 注入(最好使用模块)。
如果是这样,如何? 如果不是,有什么例子可能会绕过我提供的代码(见下文)。
一些背景:
我正在使用 Node-mysql模块创建一个 Web 应用程序,它的后端堆栈由 Node.js + MySql 组成。从可用性的角度来看,这个模块很棒,但是它还没有实现类似于 PHP 的 拟备声明的东西(尽管我知道它在 一切就绪上)。
根据我的理解,PHP 实现了预处理语句,其中包括 帮了大忙在防止 SQL 注入中的作用。但是,我担心我的 node.js 应用程序可能会受到类似的攻击 即使使用默认提供的字符串转义(如下面的代码片段所示)。
Node-mysql 似乎是 node.js 最流行的 mysql 连接器,所以我想知道其他人可能会做些什么(如果有的话)来解释这个问题——或者这是否是 node.js 的一个问题(不确定这怎么会不是,因为涉及用户/客户端输入)。
我是否应该暂时切换到 Node-mysql-原生,因为它确实提供了准备好的语句?我对这样做有些犹豫,因为它似乎不像 node-mysql 那样活跃(尽管这可能只意味着它已经完成)。
下面是一段用户注册代码,它使用了 消毒剂模块,以及 node-mysql 准备好的类似语句的语法(正如我上面提到的,它进行了字符转义) ,以分别防止跨网站脚本和 sql 注入:
// Prevent xss
var clean_user = sanitizer.sanitize(username);
// assume password is hashed already
var post = {Username: clean_user, Password: hash};
// This just uses connection.escape() underneath
var query = connection.query('INSERT INTO users SET ?', post,
function(err, results)
{
// Can a Sql injection happen here?
});