How to ensure Field Level Security in SOQL in Salesforce?

How to ensure Field Level Security in SOQL in Salesforce?

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.

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.

Example
If field access for either LastName or Description is hidden, the following SOQL query throws an exception indicating insufficient permissions.

try {
    List < Account > listAccountsWithOpptys = [
        SELECT Id, ( SELECT LastName FROM Contacts),
                                               ( SELECT Description FROM Opportunities )
                                               FROM Account WITH SECURITY_ENFORCED
    ];
    System.debug( listAccountsWithOpptys );
} catch( Exception e ) {
    System.debug( 'Exception is ' + e.getMessage() );
}

Exception if the Field Level Security is Hidden for the User’s Profile:

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.

Leave a Reply