There is nothing more dangerous than unsecured code. With unsecured code, the application is always in danger. Attackers can steal data at any time, forcefully manipulating things by tampering with requests.
Saineshwar Bageri has written 10 tips for creating a secure ASP.NET web application. You can read them at https://www.codeproject.com/Articles/1116318/Points-to-Secure-Your-ASP-NET-MVC-Applications.
You can stop an SQL injection attack with the following two techniques:
- Validations: We will discuss these later in the chapter.
- Using parameters in raw SQL queries: This is in addition to using a raw SQL query directly by concatenating values (refer to our example of unsecured code). In this way, you can rewrite the GetByProduct(string id) method as the following:
public IEnumerable<Product> GetByProduct(string id) => _context.Products
.FromSql("SELECT * FROM dbo.Products WHERE id={0}", id)
.Include(p => p.Category)
.ToList();
The preceding code still contains a raw SQL query, but it is secure enough to handle any injected code. If you try the same parameter value we used earlier, then the modified code will not accept it. It will throw an exception, as shown in the following screenshot:
You can also use string the interpolation syntax with a raw SQL query if your EF Core version is 2.0.0 or above. With string interpolation, the code looks like the following:
public IEnumerable<Product> GetByProduct(string id) => _context.Products
.FromSql($"SELECT * FROM dbo.Products WHERE id={id}")
.Include(p => p.Category)
.ToList();
- Data encryption: We will discuss this later in the chapter.