With Sharing and Without Sharing

With Sharing and Without Sharing

Apex runs in System context. By default apex is not considering about object level and field level permissions when retrieving data.

Scenario 1:

Profile Name: Standard clone user (Cloned by standard profile) , Object: Account, Field: Rating

No alt text provided for this image
No alt text provided for this image


After login from a user who is having "Standard Clone User" profile. User still can see data from the custom lightning component even though object level and field level permissions are more restrictive as above images.

No alt text provided for this image

Scenario 2:

Currently OWD setting for Accounts is set to "Private" and data are not shared using role hierarchies too to make sure that the user is only seen records created by himself.

No alt text provided for this image

If the apex class is not give "With Sharing" or explicitly giving "With Sharing" current sharing rules remains in effect where only records owned by the user will be seen according to OWD settings.

public class getAccounts {
    
    @AuraEnabled
    public static List<Account> accounts(){
        return [SELECT ID,Name,Owner.Name,Rating FROM Account];
    }


public with sharing class getAccounts {
    
    @AuraEnabled
    public static List<Account> accounts(){
        return [SELECT ID,Name,Owner.Name,Rating FROM Account];
    }


}}



No alt text provided for this image

Scenario 3:

If the apex class is used with "Without Sharing" user will see all the data and data will not restricted according to OWD settings.

public without sharing class getAccounts {
    
    @AuraEnabled
    public static List<Account> accounts(){
        return [SELECT ID,Name,Owner.Name,Rating FROM Account];
    }


}


No alt text provided for this image

Thank you,

To view or add a comment, sign in

More articles by Sameera Sevindu De Silva

  • Setting Record Create Page With Default Values

    Requirement: Opportunity can have multiple invoice records. When a new invoice record is creating…

  • Moving metadata between two unrelated Salesforce environments

    In situation where we want to migrate metadata between two related org we could use traditional change set but what if…

    2 Comments
  • OAuth 2.0 Demonstration

    Recently I was working in a integration project with constant contact V3 API to integrate with SalesForce. Initially I…

  • @testSetup method

    Creating a common method to create data will help to share record among multiple @isTest methods per class. Should be…

  • Lightning Components with Integration

    Api Used: https://jsonplaceholder.typicode.

Explore content categories