Home Salesforce Enforce Field-Level Security Permissions for SOQL Queries – Spring 19 Release

Enforce Field-Level Security Permissions for SOQL Queries – Spring 19 Release

by Dhanik Lal Sahni

New WITH SECURITY_ENFORCED clause handle checking for field- and object-level security permissions on SOQL SELECT queries, including subqueries and cross-object relationships. Although performing these 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.

To use, 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 1

If field-level security for either the LastName or Description field is hidden, this query throws an exception indicating insufficient permissions.

SELECT Id, (SELECT LastName FROM Contacts),
   (SELECT Description FROM Opportunities)
   FROM Account WITH SECURITY_ENFORCED

Example 2

If field-level security for Website is hidden, this query throws an exception indicating insufficient permissions.

SELECT Id, Parent.Name, Parent.Website FROM Account WITH SECURITY_ENFORCED

 

How to use in Apex Method

  1. Current process to Check field accessibility
           if (Schema.SObjectType.Contact.isAccessible()
                && Schema.SObjectType.Contact.fields.Name.isAccessible()
                && Schema.SObjectType.Contact.fields.Secret_Key__c.isAccessible()){
                List results = [SELECT id, Name, Secret_Key__c FROM Contact WHERE Id = :recordId];
                if (!results.isEmpty()) {
                    result = results[0];
                }
            } else{
                throw new SecurityException('You don\'t have access to all contact fields required to use this API');
            }
    
  2. New process to  Check field accessibility
            try
            {
               List results = [SELECT id, Name, Secret_Key__c FROM Contact WHERE Id = :recordId  WITH SECURITY_ENFORCED];
               if (!results.isEmpty()) {
                        result = results[0];
               }
            }
            catch( System.QueryException ex)
            {
                throw new SecurityException('You don\'t have access to all contact fields required to use this API');
            }
    

You may also like

Leave a Comment