Site icon Salesforce News Technology Stuff

Accessibility Check In SOQL Queries Using WITH SECURITY_ENFORCED

Security is very important doe any developer. In Salesforce we follow all guidelines related to security. Most of the security feature is handle by Salesforce. One of the common security feature is Object and Field level check. For this Salesforce introduce new feature WITH SECURITY_ENFORCED. Today we will check how we can use it.

This feature is still in beta and might not work as expected or Salesforce might not release it. Contact Salesforce for more details.

Previously to check read access in SOQL we need to check for each field and that increase lots of code in our class. Check below code we only have two fields but imagine we have 50+ fields in SOQL and then we need to put check for each field.

if (Schema.sObjectType.Contact.fields.Email.isAccessible() && Schema.sObjectType.Contact.fields.Phone.isAccessible()) {
   Contact c = [SELECT Email, Phone FROM Contact WHERE Id= :Id];
}

Code will be hard to maintain at the same time if we add/remove field from SOQL we also need to update these checks. What if we remove the field from SOQL but forgot to remove the check then user might get unexpected results.

To over come this we can use WITH SECURITY_ENFORCED in our SOQL and we don’t need to put these extra check as WITH SECURITY_ENFORCED handle these things out of the box. Now the same query using WITH SECURITY_ENFORCED tag will look like

Contact c = [SELECT Email, Phone FROM Contact WHERE Id= :Id WITH SECURITY_ENFORCED];

Although it can provide more details like field name so that user can quickly fix it. Its still better then the previous one and Salesforce might add that as well.

To include this in class API version must be 45 or higher.

Have you started using Lightning Web Components. If not check my post to get complete hands on experience with multiple reusable components.

Do you wants to add anything or have any question. Let me know in comments. Happy Programming 🙂

Exit mobile version