Prevent SQL Injection in JavaScript / Node.js

半城伤御伤魂 提交于 2020-05-09 04:31:48

问题


I am using Node.js to create a Discord bot. Some of my code looks as follows:

var info = {
  userid: message.author.id
}

connection.query("SELECT * FROM table WHERE userid = '" + message.author.id + "'", info, function(error) {
  if (error) throw error;
});

People have said that the way I put in message.author.id is not a secure way. How can I do this? An example?


回答1:


The best way to is to use prepared statements or queries (link to documentation for NPM mysql module: https://github.com/mysqljs/mysql#preparing-queries)

var sql = "SELECT * FROM table WHERE userid = ?";
var inserts = [message.author.id];
sql = mysql.format(sql, inserts);

If prepared statements is not an option (I have no idea why it wouldn't be), a poor man's way to prevent SQL injection is to escape all user-supplied input as described here: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#MySQL_Escaping




回答2:


Use prepared queries;

var sql = "SELECT * FROM table WHERE userid = ?";
var inserts = [message.author.id];
sql = mysql.format(sql, inserts);

You can find more information here.




回答3:


Here is the documentantion on how to properly escape any user provided data to prevent SQL injections: https://github.com/mysqljs/mysql#escaping-query-values . mysql.escape(userdata) should be enough.



来源:https://stackoverflow.com/questions/43657703/prevent-sql-injection-in-javascript-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!