Here, in this tutorial, I’ll explain what SQL injection is and how to prevent it from SQL hackers with simple login test examples in asp.net, c#, vb.net.
You can also check out my other tutorials where I’d explained about SQL defination and how to get connection string in asp.net, insert update and delete on asp.net gridview Also, more amazing tutorials on GridView, Asp.net, SQL Server here.
What is SQL Injection Attack?
This is a technique of “insertion” or “injection” of a SQL queries via webpage or webform input controls. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input to affect the execution of predefined SQL commands. It means altering SQL commands into SQL statements, and modifies database tables or data with using SQL Statements like Insert, Update or Delete.
How SQL Injection Attack Works?
Let’s say you have one login form containing UserName input in that. Generally, we enter UserName as John, Mack etc as you can see in this example statement:
SELECT * FROM UserDetails WHERE UserName=’Mack’;
But some malicious users or hackers can inject SQL commands into an SQL statement, via webpage input. Now check the following statement:
SELECT * FROM UserDetails WHERE UserName=’Mack’ or ‘1’=’1′;
See the image below, you’ll understand what I meant to say.
As you can see the WHERE clause, I’ve added UserName=’Mack’ or ‘1’=’1′, that means I added sql injection that can inject SQL command into an SQL statement.
Now the question is what is ‘1’=’1′ in that statement?
‘1’=’1′ is a Boolean condition added with sql statement, results your sql statement becomes always true. Check both statements; you’ll surely understand what it stands for. 😉
How to Prevent SQL Injection Attack?
For security reason we need to prevent the website from SQL Injections.
But the question is how?
.
I would say, by using Parameterized SQL Statements..
.
Yes, we can use parameters in sql query like SELECT * FROM UserDetails WHERE UserName=@UserName; and pass @UserName parameter value as cmd.Parameters.Add(“@UserName”, ‘aspneto’). I’ll show you an example for the same below.
Here is how your simple sql statement looks:
And following is the Parameterized sql query:
cmd.Parameters.AddWithValue(“@UserName”, txtUserName.Text);
Don’t underestimate the power of the hackers. They can guess your usernames, passwords or even database table names and perform injections. So best practice is to use prefix before your database tables like “xyz_UserDetails” and most importantly use parameterized queries instead of simple statements.
Now, it’s up to you, what you prefer most, that is your website security or SQL injections? 😉