Salesforce introduce the "
WITH SECURITY_ENFORCED" clause in Spring 19 as beta. By using
With SECURITY_ENFORCED clause in SOQL we can check the field and object level security in SOQL. To use this, just add the WITH SECURITY_ENFORCED clause in SOQL SELECT queries. If there are any fields or objects referenced in the SELECT clause that are inaccessible to the user, an exception is thrown and no data is returned
Here is sample code :-
SELECT Id, (SELECT FirstName FROM Contacts), FROM Account WITH SECURITY_ENFORCED
Now we don't need to check field accessibility in Apex using Schema function. Before to
With SECURITY_ENFORCED we used to check field level security like below
if( Schema.SObjectType.Account.Fields.Name.isAccessible() &&
Schema.SObjectType.Account.Fields.Phone.isAccessible())
{
List<Account> accList = [Select Name,Phone from Account Limit 100];
}
Now we just need to add "
With SECURITY_ENFORCED" in SOQL query like below code :-
try
{
List<Account> accList = [Select Name,Phone from Account WITH SECURITY_ENFORCED ];
} catch( System.QueryException ee) {
System.debug('You dont have access to all Account fields ');
}
Consideration
- With SECURITY_ENFORCED is available in Apex only.
- Available in API version 45.0 or greater. This is available in Beta.
Please check below post for more detail
1)
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_with_security_enforced.htm
2)
https://releasenotes.docs.salesforce.com/en-us/spring19/release-notes/rn_apex_select_with_security_enforced.htm
Thanks,
Amit Chaudhary