🔐 Preventing SOQL Injection in Apex: Secure Your Queries

🔍 What is SOQL Injection?

SOQL injection happens when an attacker enters harmful input into your application to trick a SOQL query into doing something it shouldn’t—like returning unauthorized data or changing logic. This usually happens when user input is added directly into a dynamic query without validation.

💥 Example of Unsafe Code

public static List<Contact> unsafeSearch(String searchKey) {

    String query = 'SELECT Id FROM Contact WHERE Name = \'' + searchKey + '\'';

    return Database.query(query);

}

Why it’s unsafe: 

  • In this code, the user input (searchKey) is added directly into the query string without any checks or cleaning.
  • If a user types something like: 'John%' OR Name != ' '

  • The final query becomes: SELECT Id FROM Contact WHERE Name = 'John%' OR Name != ' '

This means:

  • Instead of searching for contacts whose name is like “John%”.
  • The query now says: “Give me contacts where the name is ‘John%’ OR where the name is not empty”.
  • Since almost every contact’s name is not empty, this returns almost all contacts, ignoring the original intent.


✅ Safe Way #1: Use Static SOQL with Bind Variables

public static List<Contact> safeSearchStatic(String searchKey) {

    String key = '%' + searchKey + '%';

    return [SELECT Id FROM Contact WHERE Name LIKE :key];

}

Why it's safe:

  • Salesforce treats the entire value of searchKey as a literal string, not part of the SOQL code. So even if the user types:'John%' OR Name != ''
  • Salesforce will not try to interpret OR Name != ' ' as part of the logic. It wraps and escapes the input properly to make sure it’s treated as data only, not code. 

✅ Safe Way #2: Use Dynamic SOQL with escapeSingleQuotes()

public static List<Contact> safeSearchDynamic(String searchKey) {

    String safeKey = '%' + String.escapeSingleQuotes(searchKey) + '%';

    String query = 'SELECT Id FROM Contact WHERE Name LIKE \'' + safeKey + '\'';

    return Database.query(query);

}

Why it's safer:

  • If you're building a query as a string, this method escapes single quotes ('). That means even if a user tries to trick the system, the query stays safe.

👍 Final Tip

  • Use bind variables with static SOQL whenever you can.
  • If you must use dynamic SOQL, always escape input.
  • Never insert raw user input into your query.

🧠 Want to learn more? Check out the Salesforce guide on SOQL injection:  Salesforce Document Link


Happy Learning !


Comments

Popular posts from this blog

🚀Apex Triggers & Ownership Transfer: What Every Dev Should Know🧠