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.
As a beta feature, SELECT WITH
SECURITY_ENFORCED is a preview and isn’t part of the “Services” under your master subscription
agreement with Salesforce. Use this feature at your sole discretion, and make your purchase
decisions only on the basis of generally available products and features. Salesforce doesn’t
guarantee general availability of this feature within any particular time frame or at all, and
we can discontinue it at any time. This feature is for evaluation purposes only, not for
production use. It’s offered as is and isn’t supported, and Salesforce has no liability for
any harm or damage arising out of or in connection with it. All restrictions, Salesforce
reservation of rights, obligations concerning the Services, and terms for related
Non-Salesforce Applications and Content apply equally to your use of this feature.
Apex generally runs in system context; that is, the current user's
permissions, field-level security, and sharing rules aren’t taken into
account during code execution. 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. 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. Using WITH SECURITY_ENFORCED in
Apex classes or triggers with an API version earlier than 45.0 is not recommended.
You can use
WITH SECURITY_ENFORCED only in
SELECT and
WHERE SOQL clauses.
For example, if the user has field access for LastName, this query will return Id and LastName
for the Acme account entry.
1List<Account> act1 = [SELECT Id, (SELECT LastName FROM Contacts
2 FROM Account WHERE Name like 'Acme' WITH SECURITY_ENFORCED]
If any fields or objects referenced in the SOQL SELECT
query using WITH SECURITY_ENFORCED are inaccessible to
the user, an exception is thrown, and no data is returned.
Example
If field access for either LastName or Description is hidden, this query throws an
exception indicating insufficient permissions.
1List<Account> act1 = [SELECT Id, (SELECT LastName FROM Contacts),
2 (SELECT Description FROM Opportunities)
3 FROM Account WITH SECURITY_ENFORCED]
Example
If field access for Website is hidden, this query throws an exception indicating
insufficient permissions.
1List<Account> act2 = [SELECT Id, parent.Name, parent.Website
2 FROM Account WITH SECURITY_ENFORCED]
Example
If field access for Type is hidden, this aggregate function query throws an exception
indicating insufficient permissions.
1List<AggregateResult> agr1 = [SELECT GROUPING(Type)
2 FROM Opportunity WITH SECURITY_ENFORCED
3 GROUP BY Type]