How to ensure Field Level Security in SOQL in Salesforce?

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.

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.
view sourceprint?

List<Account> act1 = [SELECT Id, (SELECT LastName FROM Contacts),
   (SELECT Description FROM Opportunities)
   FROM Account WITH SECURITY_ENFORCED]

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.

No comments:

Post a Comment