6

I am creating an API the method below gets staff by their name in the query parameter or all staff. However, does the [FromQuery(Name = "name")] protect from SQL injection, unsure if this is a default feature of .NET core 2.2?

[HttpGet]
public IActionResult GetStaff([FromQuery(Name = "name")] string firstName)
{
    if (firstName == null)
    {
       //get all staff
       var staff = _repo.GetAllStaff().ToList();
       return Ok(staff);
    }

    if (firstName != null)
    {
       //get staff by firstName
       var staffByName = _repo.GetStaffByName(firstName).ToList();
       return Ok(staffByName);
    }

    return BadRequest("No staff found");
}

Method in Repository

    public IEnumerable<ApiStaff> GetStaffByName(string name)
    {
        var staffName = _context.ApiStaff.Where(k => k.FirstName == name);
        return staffName;
    }
theJ
  • 395
  • 5
  • 25
  • 1
    You are using an ORM. You are fine. As a general rule, unless you are concatenating a string and sending it to the database, you are fine 99% of the time. – mjwills Jan 14 '19 at 11:35

1 Answers1

9

It's unclear from your question if you are using an ORM such as entity framework, however judging from naming conventions _context and the Where linq query, I'd guess you are.

ASP.net Core does not have built in SQL injection prevention as such, in fact Asp.net core does not have request validation built into it anymore.

However using an ORM has some natural SQL injection prevention:

LINQ to Entities injection attacks:

Although query composition is possible in LINQ to Entities, it is performed through the object model API. Unlike Entity SQL queries, LINQ to Entities queries are not composed by using string manipulation or concatenation, and they are not susceptible to traditional SQL injection attacks.

This is not the case if you chose to execute SQL directly within the ORM, so it depends on how your are using it.

Security should be considered as "defence in depth", adding mitigation techniques at each layer or boundary of your application.

A simple example for your use case could be constraining first name to sensible values, for example no longer than X characters (30?), no numerics etc, however this is easier said than done for internationalization therefore even if a weakness is found in Entity Framework, then you are thwarting an attacker by only giving them a limited character set to attack you with.

I'd recommend reading OWASP's cheat sheet

Alex KeySmith
  • 16,657
  • 11
  • 74
  • 152