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.
- 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
Post a Comment