Security
Apex SOQL Injection
Preventing SOQL Injection
Apex SOQL injection uses bind variables for secure queries.
What is SOQL Injection?
SOQL Injection is a security vulnerability that occurs when an attacker manipulates a query to execute unintended commands. This can lead to unauthorized data access or modification in Salesforce applications. Similar to SQL injection, SOQL injection involves injecting malicious code into a SOQL query.
Why Use Bind Variables?
Bind variables are placeholders in your SOQL queries that safeguard against injection attacks. By using bind variables, you ensure that user input is treated as data rather than executable code. This approach not only enhances security but also optimizes query performance.
How to Implement Bind Variables in Apex
Implementing bind variables in Apex is straightforward. You can use a colon (:) followed by the variable name in your SOQL query. The Apex runtime automatically binds the variable to the query, treating it as a parameterized input.
Example of a Vulnerable SOQL Query
Consider the following example where user input is directly concatenated into a SOQL query. This approach is vulnerable to injection attacks:
Securing the Query with Bind Variables
Here's how you can secure the above query using bind variables. This method prevents attackers from modifying the query structure:
Best Practices for SOQL Security
- Always validate and sanitize user inputs.
- Use bind variables instead of string concatenation.
- Limit the fields and objects accessible within your queries.
- Implement proper user permissions and sharing rules.
- Regularly review and test your code for vulnerabilities.
Security
- Apex Sharing
- User Permissions
- SOQL Injection
- Previous
- User Permissions
- Next
- Governor Limits