Avoiding SOQL injection vulnerabilities
It is a common use case to want to receive some user input and use this as part of a SOQL query filter. However, while this provides helpful user functionality, it can be misused by a malicious user to gain access to additional data that is not meant to be visible to them.
For example, we could be searching for a contact record with the last name in the form of an input string we have defined, as shown in the following code:
public String searchName {get; set;} public PageReference search() { return Database.query('SELECT Id, FirstName, LastName, Email FROM Contact WHERE LastName Like \'%' + searchName + '%\''); }
In this preceding code, we are defining a dynamic SOQL query where, when the user enters a search term, for example, Smith
, the code will then search for contacts where the LastName
field is like Smith
, effectively running the following query:
SELECT Id, FirstName, LastName, Email FROM Contact...