Sub topic 3
What the sharing keywords control
This chapter assumes you can read basic Apex (classes, methods, SOQL) and know the record access model: organization-wide defaults (OWD), roles, and sharing rules. It also assumes you know that profiles and permission sets grant object and field permissions. The chapter covers what a sharing keyword changes and what it leaves alone. Later chapters cover each keyword in detail.
The problem the keywords solve
Apex normally runs in system mode. Your code can read and write data without checking whether the signed-in user may see or edit it. That is convenient for automation, but a controller that runs a query for a user can then return records that user could never open in the UI.
The sharing keywords are the switch that tells a class whether to apply the running user's record-level access. The running user is the user whose request started the transaction.
What a sharing keyword changes
A sharing keyword changes only record-level sharing. This is the set of rules that decides which rows a user can see or edit: OWD, the role hierarchy, sharing rules, manual shares, teams, and Apex managed sharing.
Two operations are affected:
- SOQL and SOSL queries. Under
with sharing, the query returns only the rows the user can read. Underwithout sharing, it returns every row that matches the filter. - DML. Under
with sharing, you can't insert, update, or delete a record the user lacks access to. The operation throws aDmlExceptionwith the status codeINSUFFICIENT_ACCESS_OR_READONLY. Underwithout sharing, the DML proceeds.
The keyword is a declaration on the class, so it applies to every SOQL query and DML statement in that class's methods. You can't put it on a single method.
The three keywords
Each keyword appears after the access modifier and before class.
| Keyword | Record-level sharing | Typical meaning |
|---|---|---|
| `with sharing` | Enforced for the running user | The code acts on behalf of the user |
| `without sharing` | Not enforced | The code needs to see all records, on purpose |
| `inherited sharing` | Decided by the calling class | Reusable code that should follow its caller |
A fourth case exists: a class with no keyword. Its behavior depends on how it is reached, and a later chapter covers it. For now, treat omitting the keyword as an unclear choice, not a safe default.
with sharing
public with sharing class AccountReader {
public static List<Account> getAccounts() {
// Returns only the Account records the running user can see
return [SELECT Id, Name FROM Account];
}
}If the user sees 40 of 1,000 accounts, the list holds at most 40 rows. No error is raised for the rows that are filtered out. They are missing from the results.
without sharing
public without sharing class AccountAdminReader {
public static List<Account> getAllAccounts() {
// Ignores record-level sharing for the running user
return [SELECT Id, Name FROM Account];
}
}The same query now returns all 1,000 rows. The code is identical to the first example. Only the keyword differs.
inherited sharing
public inherited sharing class AccountRepository {
public static List<Account> findByName(String name) {
return [SELECT Id, Name FROM Account WHERE Name = :name];
}
}This class has no fixed mode. It takes the mode of whichever class calls it. If it is the entry point of a transaction, with nothing calling it, it runs as with sharing. That makes it a safer choice than leaving the keyword out.
How the check works
The diagram shows where the keyword takes effect when Apex runs a query.
The first step in the diagram is the one many developers miss. Even under with sharing, system mode still applies to object permissions and field-level security. The next section explains this.
What the keywords do not control
The keywords do not enforce object permissions (CRUD) or field-level security (FLS). Those come from profiles and permission sets, and Apex ignores them by default.
public with sharing class ContactReader {
public static List<Contact> getContacts() {
// Rows are filtered by sharing, but Email is returned
// even if the user's profile cannot see the Email field
return [SELECT Id, LastName, Email FROM Contact];
}
}Suppose the user has no read access to Contact.Email. The query still returns the email values for the rows the user can see. The keyword limited the rows. It did nothing about the columns, and it would not stop the class from reading an object the user has no access to at all.
To enforce those permissions, add user-mode operations:
public with sharing class ContactService {
public static List<Contact> getContacts() {
// with sharing limits the records; USER_MODE also enforces object and field permissions
return [SELECT Id, LastName, Email FROM Contact WITH USER_MODE];
}
public static void saveContacts(List<Contact> contacts) {
Database.update(contacts, AccessLevel.USER_MODE);
}
}Here the two mechanisms work together. with sharing handles rows. USER_MODE handles object and field permissions, and it also applies the user's record sharing to that statement. A later chapter covers it in detail.
The next table summarizes who enforces what in Apex.
| Concern | Enforced by default in Apex? | How to enforce it |
|---|---|---|
| Which records the user can access | No | `with sharing` or `inherited sharing` |
| Object permissions (CRUD) | No | `WITH USER_MODE`, `AccessLevel.USER_MODE` |
| Field-level security | No | `WITH USER_MODE`, `AccessLevel.USER_MODE` |
A short experiment
This anonymous Apex snippet shows the effect. It assumes you have an org where your user cannot see every Case. The first class limits the count and the second does not.
public with sharing class CaseController {
public static Integer countVisibleCases() {
return [SELECT COUNT() FROM Case];
}
public static Integer countAllCases() {
// The method runs under the sharing mode of the class that defines it
return CaseCounter.countAll();
}
}
public without sharing class CaseCounter {
public static Integer countAll() {
return [SELECT COUNT() FROM Case];
}
}Calling CaseController.countVisibleCases() returns the number of Cases the user can see. Calling CaseController.countAllCases() returns every Case, even though the call started in a with sharing class. The reason is that each method runs under the sharing mode of the class that defines it. countAll is defined in CaseCounter, so it uses without sharing. The chapter on call chains explains this rule fully.
Here is a failing write, to see the DML effect:
public with sharing class CaseUpdater {
public static String tryClose(Id caseId) {
Case c = new Case(Id = caseId, Status = 'Closed');
try {
update c;
return 'Updated';
} catch (DmlException e) {
// Thrown when the user lacks edit access to this record
return 'Blocked: ' + e.getDmlStatusCode(0);
}
}
}If the running user can only read this Case, the method returns Blocked: INSUFFICIENT_ACCESS_OR_READONLY. If the same logic lived in a without sharing class, the update would succeed.
Edge cases to know
- View All Data and Modify All Data. A user with either permission already has access to every record, so
with sharingfilters nothing for them. A test with such a user, such as an administrator, will not reveal a missing keyword. - The keyword names a rule, not a user. Apex does not switch to a different user. The running user stays the same, and only the record-access check changes.
- Per-class, not per-transaction. One transaction can run some code under
with sharingand other code underwithout sharing, depending on which class owns each method. - Not a security boundary on its own. Because the keyword leaves CRUD and FLS alone, a class that is
with sharingcan still leak fields. Treat it as one control among several.
Summary of the model
Apex starts with no restrictions. A sharing keyword puts back one of them: the user's record-level access. with sharing puts it back, without sharing leaves it off on purpose, and inherited sharing defers to the caller. Object and field permissions need a separate mechanism.
Exercise
A with sharing class runs SELECT Id, Salary__c FROM Employee__c. The running user can see 10 of the 50 Employee_c records, but their profile has no read access to the Salaryc field. How many rows come back, and are the Salary_c values included? What change would stop the field values from being returned?
Show answer
10 rows come back, because with sharing limits the rows to the records the user can see. The Salary_c values are included, because Apex runs in system mode and the keyword does not enforce field-level security. Adding `WITH USERMODE to the query (or using Database.query with AccessLevel.USER_MODE`) applies the user's object and field permissions. The query then fails with a security error instead of returning the field.
Exercise
A class declared without sharing has a method that updates an Opportunity. A user who has only read access to that Opportunity calls it. Does the update succeed? What would happen if the class were declared with sharing?
Show answer
The update succeeds, because without sharing does not apply the user's record-level access to DML. If the class were with sharing, the update would throw a DmlException with the status code INSUFFICIENT_ACCESS_OR_READONLY.