Sub topic 4
with sharing: enforcing the user's record access
This chapter assumes you know basic Apex syntax and SOQL. It also assumes you know how organization-wide defaults, roles, and sharing rules decide which records a user can see. Earlier chapters covered why Apex runs in system context by default. Here you will see what with sharing changes.
What the keyword does
with sharing makes the class respect the running user's record-level access. The running user is the person whose action started the transaction. Their access comes from organization-wide defaults, the role hierarchy, sharing rules, manual shares, and team access.
The effect applies to the SOQL queries and DML statements written in that class:
- A query returns only the records the user can see. Other records are silently left out. No error is raised.
- A DML statement on a record the user cannot edit fails with an exception.
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 a user sees 40 of 500 accounts, this method returns 40 rows.
How a query is filtered
Handling the two failure styles
The silent filtering of queries can surprise you in two ways.
First, assigning a query result directly to a single record fails if the user cannot see a match. The query returns zero rows, and Apex throws a QueryException. Query into a list and check it instead.
Second, DML on a record the user can read but not edit throws a DmlException. Its status code is INSUFFICIENT_ACCESS_OR_READONLY. Catch it where you can give the user a useful message.
public with sharing class AccountRenamer {
public static String rename(Id accountId, String newName) {
List<Account> matches = [
SELECT Id, Name FROM Account WHERE Id = :accountId LIMIT 1
];
if (matches.isEmpty()) {
return 'Account not found or not visible to you.';
}
matches[0].Name = newName;
try {
update matches;
} catch (DmlException e) {
return 'Update failed: ' + e.getDmlMessage(0);
}
return 'Renamed.';
}
}What with sharing does not cover
with sharing governs which records the user can reach. It does not check object permissions (CRUD) or field-level security (FLS). A user with no access to the Contact object, or to a particular field, can still have that data returned by a with sharing class unless you enforce permissions separately. A later chapter covers user-mode queries and DML for that purpose.
Scope of the keyword
The keyword applies to the code in the class that declares it. When a with sharing class calls a class declared without sharing, the called method runs under its own class's mode. The chapter on call chains covers this in detail. For now, remember that adding with sharing to one class does not make everything it calls safe.
Common errors
| Mistake | Result |
|---|---|
| Assuming `with sharing` enforces field-level security | Fields the user cannot read may still be returned |
| Querying into a single record variable | `QueryException` when the user cannot see the record |
| Expecting an error for hidden records in a query | None. The rows are simply missing |
| Not catching `DmlException` | The user sees a raw error instead of a clear message |
Exercise
A user can see 40 of 500 Account records. A with sharing class runs [SELECT Id FROM Account] and then update on one of the 40 records, which the user can read but not edit. What do the query and the update do?
Show answer
The query returns 40 rows and raises no error. The update throws a DmlException with status code INSUFFICIENTACCESSOR_READONLY, because the user has read but not edit access to that record.