Salesforce Inherited sharing
As of Winter ’19, we can use inherited sharing in an apex class signature. The “Inherited Sharing” feature allows us to run our apex code either with or without sharing settings, depending on the context in which it was called.
- This allows the class to run in the same mode as the class which called it. Apex classes with Inherited Sharing that are called from other classes with no sharing settings will run in no sharing mode.
- Assures that privileged Apex code is not used in unexpected or insecure ways and passes security review.
- If a class is declared as Inherited Sharing, it runs as with sharing by default.
public inherited sharing class InheritedSharingClass {
public List<Contact> getAllTheSecrets() {
return [SELECT Id,Name FROM Contact];
} }
Note When an Apex class has inherited sharing, it differs from one that has omitted sharing. Class entry points are treated as “without sharing” if a sharing declaration is omitted. However, inherited sharing makes it default to run as it does with sharing. A class declared as inherited sharing only runs without sharing if it is explicitly called from a context that already exists without sharing.
Some of the basic concepts we should be to analyze. The below points taken from (https://salesforce.stackexchange.com/questions/264509/inherited-sharing-vs-no-sharing-declaration)
- If a class with
without sharing
is calling the method of a class withinherited sharing
, then it will run inwithout sharing
mode. - If a class with
with sharing
is calling the method of a class withinherited sharing
, then it will run inwith sharing
mode. - If a class with
omitted sharing
(i.e. no sharing is mentioned) is calling the method of a class withinherited sharing
, then it will run inwithout sharing
mode as the default sharing mode of theomitted sharing
is to run inwithout sharing
mode (This is because the calling class is established as awithout sharing
context). A class declared asinherited sharing
runs aswithout sharing
only when explicitly called from an already establishedwithout sharing
context. - If a class with
with sharing
is calling a method of a class withomitted sharing
which in turn calls a method of a class withinherited sharing
, then it will run inwith sharing
mode, as the calling class is inwith sharing
mode and omitted class is established aswith sharing
context. - If a class with
without sharing
is calling a method of a class withomitted sharing
which in turn calls a method of a class withinherited sharing
, then it will run inwithout sharing
mode, as the calling class is inwithout sharing
mode and the omitted class is established aswithout sharing
context. - If the class is used as the entry point to an Apex transaction, an
omitted sharing
declaration runs aswithout sharing
. - If the class is used as the entry point to an Apex transaction,
inherited sharing
ensures that the default is to run aswith sharing
.