In a Salesforce Apex class, we can define the sharing settings to control data access and ensure security within the Salesforce platform. To manage how Apex classes follow record-level access, we use keywords such as with sharing, without sharing, inherited sharing, and omitted sharing in Salesforce Apex.
In this blog, we’ll learn what each of these sharing keywords means, when to use them, and how they affect data visibility in the Apex code.
What is the Use of Sharing Keywords in the Apex Class?
In Salesforce, the sharing model record-level security is managed through Profiles, Sharing settings, Ownership, Role Hierarchy, and Sharing rules. By using the “Sharing keyword“, we can ensure that the apex class we created follows to Salesforce’s record-level sharing rules, which are based on OWD, role hierarchies, and sharing rules.
By default, Apex code runs in system context, which can bypass these rules and expose data that the user should not usually see. To manage this, Apex provides four sharing options: with sharing, without sharing, inherited sharing, and omitting the sharing keyword.
Let’s see the implementation and use case of these four sharing keywords in Salesforce Apex.
Use case scenario:
Let’s consider a scenario where there is a custom object Project_c, and project records are shared by the CEO and the manager. In the Salesforce role hierarchy, the CEO is above the manager, so he will be able to access all project records, but the manager can only share those records owned or shared with him.
To show the output according to sharing rules, I have assigned the CEO role to my profile and the manager role to another user with a Salesforce platform license.
With Sharing Keyword in Salesforce Apex
In a Salesforce Apex class, when we use the ‘With sharing‘ keyword, the code runs in the context of the current user, which means it enforces the sharing rules for the current user. When we use the “With sharing” keyword, then records not shared with the current user are not accessed by the apex code in this context.
According to the above-mentioned scenario, we will run the apec class in the context of a user with a manager role. In this Apex class, we will use the “with sharing” so the code will follow the sharing rules in the context of the current user.
public with sharing class ApexWithSharing {
public static List<Project__c> getAllProjects() {
return [
SELECT Id, Name, Status__c, Owner.Name
FROM Project__c
ORDER BY CreatedDate DESC
];
}
}
Now, enter the code below in the anonymous window to execute the apex class method.
List<Project__c> projects = ApexWithSharing.getAllProjects();
for (Project__c project : projects) {
System.debug('Project Name: ' + project.Name +
', Status: ' + project.Status__c +
', Owner Name: ' + project.Owner.Name);
}
In the Execution log window, select the ‘Debug only‘ checkbox, and you will see the records owned by the current user.
