Newer Version Available
Enforce Sharing Rules
Apex developers must take care not to inadvertently expose sensitive data that would normally be hidden from users by user permissions, field-level security, or organization-wide defaults. They must be particularly careful with Web services, which can be restricted by permissions, but execute in system context after they’re initiated.
Most of the time, system context provides the correct behavior for system-level operations such as triggers and Web services that need access to all data in an organization. However, you can also specify that particular Apex classes should enforce the sharing rules that apply to the current user.
This example has two classes, the first class (CWith) enforces sharing rules while the second class (CWithout) doesn’t. The CWithout class calls a method from the first, which runs with sharing rules enforced. The CWithout class contains an inner class, in which code executes under the same sharing context as the caller. It also contains a class that extends it, which inherits its without sharing setting.
Enforcing the current user's sharing rules can impact:
- SOQL and SOSL queries. A query can return fewer rows than it would operating in system context.
- DML operations. An operation can fail because the current user doesn't have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user doesn’t have access to, then the DML operation fails.