Enforce Field-Level Security Permissions for SOQL Queries

  • Using WITH SECURITY_ENFORCED clause we can enforce Field-Level Security Permissions on SOQL SELECT queries, including subqueries and cross-object relationships.
  • The WITH SECURITY_ENFORCED clause is only available in Apex. Using WITH SECURITY_ENFORCED in Apex classes or triggers with an API version earlier than 45.0 is not recommended.
  • If fields or objects referenced in the SELECT clause using WITH SECURITY_ENFORCED are inaccessible to the user, an exception is thrown, and no data is returned.

Example:

If the Contact Email & Phone fields permission is not accessible to the user, it will throw an exception insufficient permissions and no data will return.

SELECT Id, Name, (SELECT Email, Phone FROM Contacts) FROM Account WITH SECURITY_ENFORCED

If the Account Website filed permission is not accessible to the user, it will throw an exception insufficient permissions and no data will return.

SELECT Id, Name, Website FROM Account WITH SECURITY_ENFORCED