SQL Injection

SQL Injection is a security vulnerability that lets an attacker manipulate the SQL queries your application sends to the database.

It happens when user input is directly added to SQL queries without proper sanitization or prepared statements.

Example of a vulnerable function

function login(username, password) {
  const query = `
    SELECT * FROM users
    WHERE username = '${username}'
    AND password = '${password}'
  `;

  return database.exec(query);
}

If we set username to:

' OR 1=1 --

The final SQL becomes:

SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''

This query will always return true, give a list of all users, and the app will probably pick the first one.

This allows us to easily bypass the login.

How to Prevent SQL Injection

Try it yourself

Here’s a vulnerable login form demo. You can enter your own inputs and see the generated SQL query, then try to break it with SQL injection.

Login

Query

SELECT * FROM users
WHERE username = ''
AND password = ''

Response


Find this post helpful? Subscribe and get notified when I post something new!