Do es6 template literals protect against sql injection?

我的未来我决定 提交于 2019-12-23 17:54:33

问题


Do es6 template literals, when used to construct queries, protect against SQL injection? Can you provide some examples of common attacks and how they would be mitigated?

More specifically, I plan to use the mssql module in a node project. In their documentation under the template literals section it says "All values are automatically sanitized against SQL injection". Is this true purely because of how ES6 template literals work?


回答1:


No, ES6 template literals are just another way to build strings and don't protect you against SQL injections if you were to use them to build raw SQL queries from supplied user input without additional filtering / escaping:

let name = "Robert'; DROP TABLE Students;--"; // user supplied input

let sql = `SELECT * FROM Students WHERE name = '${name}'`; // build query...

console.log(sql); // Injected SQL!



回答2:


Yes, but only if you use an appropriate tag. When you use tags, it's called a Tagged Template Literal though. The tag goes right before the first backtick.

You can use sql.query by node-mssql as a tag or https://github.com/TehShrike/sql-tagged-template-literal

const SQL = require('sql-template-strings');
let name = "Robert'; DROP TABLE Students;--"; // user supplied input

let sql = SQL`SELECT * FROM Students WHERE name = '${name}'`; // build query...

console.log(sql); // Non-injected SQL!

// SELECT * FROM Students WHERE name = 'Robert''; DROP TABLE Students;--'

Tip! editors may automatically syntax highlight the SQL inside the template literal if it uses the sql tag.



来源:https://stackoverflow.com/questions/44086785/do-es6-template-literals-protect-against-sql-injection

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