No comments yet

Field Level Security in SOQL With SECURITY_ENFORCED

By using With SECURITY_ENFORCED clause in SOQL we can enforce the field and object level security in SOQL. To use this, just add the WITH SECURITY_ENFORCED clause in SOQL SELECT queries. If there are any fields or objects referenced in the SELECT clause that are inaccessible to the user, an exception is thrown and no data is returned.

Example of With SECURITY_ENFORCED

Let see how we can enforce the Field Level Security in SOQL With SECURITY_ENFORCED. Here is example of With SECURITY_ENFORCED.

SELECT Id, (SELECT FirstName FROM Contacts), FROM Account WITH SECURITY_ENFORCED

Now we don’t need to check field accessibility in Apex using Schema function. Before to With SECURITY_ENFORCED we used to check field level security like below

if( Schema.SObjectType.Account.Fields.Name.isAccessible() &&
    Schema.SObjectType.Account.Fields.Phone.isAccessible())
{
    List<Account> accList = [Select Name,Phone from Account Limit 100];
}

Now we just need to add With SECURITY_ENFORCED in SOQL query like below code.

try {
  List<Account> accList = [Select Name,Phone from Account WITH SECURITY_ENFORCED ];
} catch(System.QueryException ee) {
    System.debug('You dont have access to all Account fields ');
}

Consideration

  1. With SECURITY_ENFORCED is available in Apex only.
  2. Available in API version 45.0 or greater.

What is the difference between WITH SECURITY_ENFORCED and WITH SHARING?

Now question is what is the use of With Sharing? When we use with sharing keyword then we are enforcing the record access. Means it will return records base on sharing rule, OWD or ownership. On the other hand WITH SECURITY_ENFORCED keyword enforce Field and Object level security.

Enforcing Object & FLS Permissions in Apex

Apex doesn’t enforce object-level and field-level permissions by default. Let see how we can enforce the CRUD & FLS in Apex.

Read data (SOQL)Modify data (DML)
Schema methodsYesYes
WITH SECURITY_ENFORCEDYesNo
Security.stripInaccessible()YesYes
Database operations in user mode (pilot)YesYes

Learn more about security in Apex here.

Summary

Use the WITH SECURITY_ENFORCED clause to enable field- and object-level security permissions checking for SOQL SELECT queries in Apex code.

Post a comment