Enforce Field-Level Security Permissions for SOQL Queries

  • In Spring ’19 Release Salesforce has introduced WITH SECURITY_ENFORCED clause, you can use this to enable checking for field- and object-level security permissions on SOQL SELECT queries, including subqueries and cross-object relationships.
  • Currently if you include a field in a SQOL query (Without WITH SECURITY_ENFORCED Clause) and a user doesn’t have access to that field, the field will be returned and can be used by the code without any exception, but the data to that user should not have access.
  • If you use WITH SECURITY_ENFORCED clause for same SOQL Select query, it will throw exception and no data will be returned.
  • This feature is tailored to Apex developers who have minimal development experience with security and to applications where graceful degradation on permissions errors isn’t required. The WITH SECURITY_ENFORCED clause is only available in Apex.
  • 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.

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