SOQL Injection in Apex Salesforce

An SOQL Injection in Apex is computer attack to steal data from your database. Hence this is important to prevent SOQL Injection in Apex while writing query to select data from database. In Apex you can write Select query in two ways.
1. Inside brackets like [].

Example:- If you want to get all contact where name end with xyz. Then your select query will be like

String likeStr='%xyz';

List<Contact> conList = [Select Id,FirstName,LastName from Contact Where name like : likeStr];
System.debug(conList);

In this type of query Salesforce by default apply SOQL Injection. We do not required to explicit write extra code for SOQL Injection in Apex class
OUTPUT

(Contact:{Id=0037djdddkdkdkdk, FirstName=Andy, LastName=xyz})

2. Database.query() or Database.countQuery().

Example:- If you want to get all contact where name end with xyz. Then your select query will be like

String likeStr='%xyz';

List<Contact> conList = Database.query('Select Id,FirstName,LastName from Contact Where name like \''+String.escapeSingleQuotes(likeStr)+'\'');

System.debug(conList);

Note:

Focus on dynamic query which are build by concatenate multiple string and use Escaping Single Quotes for all variable used in query. For escaping single quotes use simple static method of String class(String.escapeSingleQuotes(variableName)).

Leave a Reply

Your email address will not be published. Required fields are marked *