Tag Archives: Field Level Security

Enforce Field-Level Security Permissions for SOQL Queries

  • In Spring ’19 Release Salesforce has introduced WITH SECURITY_ENFORCED clause, you can use this to enable checking for field- and object-level security permissions on SOQL SELECT queries, including subqueries and cross-object relationships.
  • Currently if you include a field in a SQOL query (Without WITH SECURITY_ENFORCED Clause) and a user doesn’t have access to that field, the field will be returned and can be used by the code without any exception, but the data to that user should not have access.
  • If you use WITH SECURITY_ENFORCED clause for same SOQL Select query, it will throw exception and no data will be returned.
  • 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. The WITH SECURITY_ENFORCED clause is only available in Apex.
  • 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.

Example:

If the Contact Email & Phone fields permission is not accessible to the user, it will throw an exception insufficient permissions and no data will return.

SELECT Id, Name, (SELECT Email, Phone FROM Contacts) FROM Account WITH SECURITY_ENFORCED

If the Account Website filed permission is not accessible to the user, it will throw an exception insufficient permissions and no data will return.

SELECT Id, Name, Website FROM Account WITH SECURITY_ENFORCED

Check Profile Based Field Level Security Using Apex

For Specific Profile :

List<FieldPermissions> fpList = [SELECT SobjectType, Field, PermissionsRead, PermissionsEdit, Parent.ProfileId FROM FieldPermissions WHERE SobjectType = 'Account' and Field='Account.Customer_Priority__c' AND Parent.ProfileId IN (SELECT Id FROM PermissionSet WHERE PermissionSet.Profile.Name = 'System Administrator')];
if(!fpList.isEmpty()){
    Boolean hasReadPermission = fpList[0].PermissionsRead;
    Boolean hasEditPermission = fpList[0].PermissionsEdit;
    system.debug('Read Permission - ' + hasReadPermission);
    system.debug('Edit Permission - ' + hasEditPermission);
}

For Current User :

List<FieldPermissions> fpList = [SELECT SobjectType, Field, PermissionsRead, PermissionsEdit, Parent.ProfileId FROM FieldPermissions WHERE SobjectType = 'Account' and Field='Account.Customer_Priority__c' AND Parent.ProfileId=:Userinfo.getProfileId()];
if(!fpList.isEmpty()){
    Boolean hasReadPermission = fpList[0].PermissionsRead;
    Boolean hasEditPermission = fpList[0].PermissionsEdit;
    system.debug('Read Permission - ' + hasReadPermission);
    system.debug('Edit Permission - ' + hasEditPermission);
}