Object and Field Level Permissions Check Using WITH SECURITY_ENFORCED in SOQL Query

Object and Field Level Permissions Check Using WITH SECURITY_ENFORCED in SOQL Queries is available from API version 45.0 including subqueries and cross-object relationships.

Example:-

If the Email field from Contact Object permission is not accessible to the user, it will throw an exception insufficient permissions and no data will return.

List<Account> act1 = [SELECT Id, (SELECT Email FROM Contacts) FROM Account WHERE Name like 'Test' WITH SECURITY_ENFORCED];

If theWebsite field from Account Object permission is not accessible to the user, it will throw an exception insufficient permissions and no data will return.

List<Account> act2 = [SELECT Id, Name, Website FROM Account WITH SECURITY_ENFORCED];

Usage consideration :-

The WITH SECURITY_ENFORCED clause is not recommended to use in Apex classes or triggers with an API version earlier than 45.0.

Also this applies field- and object-level security checks only to fields and objects referenced in SELECT or FROM SOQL clauses and not clauses like WHERE or ORDER BY. In other words, security is enforced on what the SOQL SELECT query returns, not on all the elements that go into running the query.

Apex generally runs in system context; that is, the current user’s permissions and field-level security aren’t taken into account during code execution. Sharing rules, however, are not always bypassed: the class must be declared with the without sharing keyword in order to ensure that sharing rules are not enforced. Although performing field- and object-level security checks was possible in earlier releases, this clause substantially reduces the verbosity and technical complexity in query operations.

Be the first to comment

Leave a Reply

Your email address will not be published.


*