What methods can be used to protect an application from malicious SQL injection?
sobes.tech AI
Answer from AI
The following methods are used to protect a Node.js application from malicious SQL injection attacks:
-
Using parameterized queries (prepared statements): instead of concatenating strings with user data, use parameters that the database driver handles safely.
-
ORMs and libraries with injection protection: such as Sequelize, TypeORM, Knex, which automatically escape parameters.
-
Validation and sanitization of input data: check and clean data received from users to exclude dangerous characters.
-
Using ORM or query builders: they help construct queries safely, reducing the risk of errors.
-
Minimizing database access rights: the database user under which the application operates should have the minimum necessary permissions.
Example of a parameterized query using mysql2:
const mysql = require('mysql2/promise');
async function getUserById(userId) {
const connection = await mysql.createConnection({host:'localhost', user:'root', database:'test'});
const [rows] = await connection.execute('SELECT * FROM users WHERE id = ?', [userId]);
await connection.end();
return rows;
}
In this example, the value userId is not inserted directly into the query string but is passed as a parameter, which prevents SQL injection.