Enforcing permissions and security within SOQL
When we discussed enforcing sharing rules earlier in this chapter, we noted how the use of the with sharing
keywords on a class declaration would ensure that any query run within that class has the sharing rules for the user enforced upon the query. We also saw, in the Enforcing object and field permissions section, how we can work with results returned from a query and enforce permissions on these records using the stripInaccessible
method.
In the Spring '20 release, Salesforce added the WITH SECURITY_ENFORCED
clause to the SOQL language. Unlike the stripInaccessible
method, if the user is lacking permissions for a field, an exception is thrown rather than the field simply being removed.
To apply this clause, we simply include WITH SECURITY_ENFORCED
after any WHERE
clause and before any ORDER BY
, LIMIT
, OFFSET,
or aggregate function clauses. For example, consider the following:
List<Contact> = [SELECT FirstName, LastName...