Using WITH SHARING and WITHOUT SHARING keywords

In Salesforce Apex, the with sharing and without sharing keywords are used to control the sharing behavior of data queried or manipulated within a class. These keywords enforce the sharing rules defined in Salesforce for the current user executing the Apex code.


Here's how these keywords work:

with sharing: When a class is declared with the with sharing keyword, the sharing rules defined in Salesforce are enforced. This means that the class respects the organization-wide defaults (OWD), role hierarchies, sharing rules, and manual sharing settings. Users only have access to records they are permitted to see according to these rules.

public with sharing class MyClass {

    // Apex code here

}

without sharing: When a class is declared with the without sharing keyword, the sharing rules defined in Salesforce are bypassed. This means that Apex code within the class runs in system context and ignores any sharing rules, allowing it to access all records regardless of the user's sharing permissions.

public without sharing class MyClass {
    // Apex code here
}


Use with sharing: Use with sharing when you want to enforce the sharing rules defined in Salesforce and ensure that users only have access to records they are authorized to see. This is the default behavior for Apex classes if neither with sharing nor without sharing is specified.

Use without sharing: Use without sharing when you need to perform operations in system context and explicitly bypass the sharing rules. Be cautious when using without sharing, as it can potentially expose sensitive data to users who shouldn't have access to it based on sharing settings.

Best Practices:

  • Always consider security and access control when choosing whether to use with sharing or without sharing.
  • Use with sharing by default to enforce sharing rules and minimize the risk of data exposure.
  • Only use without sharing when necessary and ensure that proper security measures are in place to prevent unauthorized access to sensitive data.
  • It's important to note that the with sharing and without sharing keywords only affect the behavior of the Apex code within the class where they are specified. They do not affect the sharing behavior of other classes or components interacting with the data.

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach