Thursday 3 January 2019

Inherited Sharing | Apex Inherited Sharing | Winter ’19


Now we can use "Inherited Sharing" in a apex class signature from Winter ’19. With "Inherited Sharing" we can run our apex code with both with or without sharing settings, depending on the context it is being called from.
  1. Allows the class to run in the sharing mode of the class that called it. If Apex class with Inherited Sharing is being called from some other class which is having without sharing setting, then it will run in without sharing mode.
  2. Enables you to pass security review and ensure that your privileged Apex code is not used in unexpected or insecure ways.
  3. If a class declared as Inherited Sharing, it runs as with sharing by default.
Example :-
Here is example of declaring an Apex class with inherited sharing and a Visualforce calling of that Apex code. With inherited sharing declaration, only contacts for which the running user has sharing access will display. But if the declaration is omitted, even contacts that the user has no rights to view are displayed due to the insecure default behavior of omitting the declaration.

Apex Class:-
public inherited sharing class Inherited_Sharing_Class{
    public List<Contact> getContacts(){
        return [SELECT Name FROM Contact];
    }
}

VF Page:-
<apex:page controller="Inherited_Sharing_Class">
    <apex:repeat value="{!Contacts}" var="record">
        {!record.Name}
    </apex:repeat>
</apex:page>


Thanks
Amit Chaudhary


4 comments:

  1. How would it behave if called from a trigger instance?

    ReplyDelete