When writing Apex code in Salesforce, it’s important to protect data by checking user permissions like Field-Level Security (FLS) and Object-Level Security (OLS). One way to do this is by using WITH SECURITY_ENFORCED in your SOQL queries.
This keyword tells Salesforce to check if the current user has access to the fields and objects in the query. If the user doesn’t have access, the query fails and throws an error. This helps avoid showing data that the user shouldn’t see.
Account[] accts = [SELECT Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];
In this example, Salesforce checks if the user can access the Name and AnnualRevenue fields. If not, it will stop the query and show an error.
Salesforce Recommendation: Use USER_MODE Instead
Salesforce recommends using WITH USER_MODE instead of WITH SECURITY_ENFORCED because it has fewer limitations and works better in more situations.
With USER_MODE, your Apex code runs as if it were the user, automatically respecting all their permissions—without needing extra checks.
For more details on user mode please refer blog https://www.sfdc-lightning.com/2025/06/user-mode-in-apex-new-way-to-respect.html
Important Notes:
Don’t use WITH SECURITY_ENFORCED and USER_MODE together in the same query.
If you switch to USER_MODE, remove any WITH SECURITY_ENFORCED clauses—they’re not needed.
Using both together will cause errors.
Limitations of WITH SECURITY_ENFORCED:
- Works only with SOQL
WITH SECURITY_ENFORCED works only in SOQL queries. It cannot be used with SOSL or DML.
Valid Example:
Account[] accs = [SELECT Name FROM Account WITH SECURITY_ENFORCED];
- Does not support relationship fields
You cannot use relationship fields like Owner.Name in the query.
Invalid Example:
[SELECT Name, Owner.Name FROM Account WITH SECURITY_ENFORCED];
- Cannot be used in dynamic SOQL
WITH SECURITY_ENFORCED does not work in queries written as strings and executed at runtime.
Invalid Example:
String soql = 'SELECT Name FROM Account WITH SECURITY_ENFORCED';
Database.query(soql); // This will fail
- Exceptions cannot be caught
If the user doesn’t have access to a field or object, the query throws an exception that cannot be handled with try-catch.
Invalid Example:
try {
[SELECT Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];
} catch (Exception e) {
// This will not catch the error
}
- No partial access allowed
If the user lacks access to even one field, the entire query fails. It does not return partial results.
Example:
[SELECT Name, AnnualRevenue FROM Account WITH SECURITY_ENFORCED];
No comments:
Post a Comment