Enable Field- and Object-Level Permissions Checking Using WITH SECURITY_ENFORCED in SOQL Queries (Generally Available)

SOQL queries using WITH SECURITY_ENFORCED is now generally available. Use the WITH SECURITY_ENFORCED clause to enable field and object level security permissions checking for SOQL SELECT queries in Apex code, including subqueries and cross-object relationships. The WITH SECURITY_ENFORCED clause is available only in Apex.

Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

How: We don’t recommend using WITH SECURITY_ENFORCED in Apex classes or triggers with an API version earlier than 45.0. There is a new restriction while querying polymorphic lookup fields using WITH SECURITY_ENFORCED. Polymorphic lookup fields are relationship fields that can point to more than one entity.
  • Traversing a polymorphic field’s relationship is not supported in queries using WITH SECURITY_ENFORCED. For example, you cannot use WITH SECURITY_ENFORCED in this query, which returns the Id and Owner names for User and Calendar entities: SELECT Id, What.Name FROM Event WHERE What.Type IN ('User','Calendar').
  • Using TYPEOF expressions with an ELSE clause is not supported in queries using WITH SECURITY_ENFORCED. TYPEOF is used in a SELECT query to specify the fields to be returned for a given type of a polymorphic relationship. For example, you cannot use WITH SECURITY_ENFORCED in this query. The query specifies certain fields to be returned for Account and Opportunity objects, and Name and Email fields to be returned for all other objects.
    SELECT 
    TYPE OF What 
       WHEN Account THEN Phone 
       WHEN Opportunity THEN Amount 
       ELSE Name,Email 
    END 
    FROM Event
  • The Owner, CreatedBy, and LastModifiedBy polymorphic lookup fields are exempt from this restriction, and do allow polymorphic relationship traversal.
  • For AppExchange Security Review, you must use API version 48.0 or later when using WITH SECURITY_ENFORCED. You cannot use API versions where the feature was in beta or pilot.