Sub topic 14
Sharing Behavior in Apex: with sharing and Share Records
This chapter assumes you know org-wide defaults, the role hierarchy, and how sharing rules, teams, and manual sharing open access. It also assumes basic Apex and SOQL. It covers two things. The first is whether Apex code respects the sharing model. The second is how Apex reads and writes the share rows that implement that model.
Apex runs in system mode by default
Apex normally runs in system mode. It ignores the running user's object permissions, field permissions, and record sharing. A query in a class with no sharing keyword can return records the user could never open in the UI.
The with sharing keyword changes one part of this. It makes the class respect record-level sharing for the running user. That covers org-wide defaults, role hierarchy, sharing rules, teams, and manual shares.
public with sharing class AccountReader {
public static List<Account> visibleAccounts() {
return [SELECT Id, Name, OwnerId FROM Account ORDER BY Name LIMIT 50];
}
}If the running user's org-wide default for Account is Private, this returns only accounts the user owns, accounts below them in the hierarchy, and accounts shared to them. A user with View All on Account sees every account, because View All bypasses sharing.
The three sharing keywords
| Declaration | Record sharing | Typical use |
|---|---|---|
| `with sharing` | Enforced for the running user | Controllers, services called from the UI or API |
| `without sharing` | Not enforced | Narrow system tasks, such as writing share rows or rollups across all records |
| `inherited sharing` | Uses the caller's mode. As an entry point it runs `with sharing` | Utility and service classes reused from many callers |
| No keyword | Inherited when called from another class. Entry points have historically behaved like `without sharing` | Avoid. Always declare a keyword |
Some rules affect the table:
- Sharing is set per class. A
with sharingclass that calls awithout sharingclass runs the called code without sharing, and returns to enforcement when control comes back. - Inner classes do not inherit the outer class's sharing. Declare it on each inner class.
- Triggers always run in system mode, so a trigger cannot enforce sharing by itself. Have it call a
with sharingclass if it needs that. - Anonymous Apex and the Developer Console run as the current user, but exposure through the keyword rules is the same.
Sharing does not enforce object or field permissions
with sharing answers one question: which records can this user see? It does not check whether the user has Read on the object or access to a field. Both of these can still happen in a with sharing class:
- A user without Read on Account queries accounts and gets results.
- A user without field access reads a restricted field.
To enforce those layers, add one of these:
WITH USER_MODEon the query, which applies object permissions, field-level security, and sharing.Security.stripInaccessible()to remove fields the user cannot read or write.WITH SECURITY_ENFORCED, an older option that checks fields but not sharing.
public with sharing class SafeAccountReader {
public static List<Account> visibleAccounts() {
return [SELECT Id, Name, OwnerId FROM Account WITH USER_MODE ORDER BY Name LIMIT 50];
}
}Using without sharing safely
Some work legitimately needs all records. An example is a duplicate check that must see accounts outside the user's access. Keep without sharing small and put it in its own class. That makes it easy to review.
public with sharing class LeadService {
public static Boolean domainExists(String domain) {
return DomainLookup.exists(domain);
}
private without sharing class DomainLookup {
static Boolean exists(String domain) {
return ![SELECT Id FROM Account WHERE Website = :domain LIMIT 1].isEmpty();
}
}
}The inner class returns only a Boolean, not the records. That limits what leaks to a user who lacks access.
Share tables
Each object that can have restricted access has a share table. Account has AccountShare, Contact has ContactShare, and a custom object Project__c has Project__Share. Rows exist only when the org-wide default is not Public Read/Write. Each row gives one user or group an access level, and its RowCause says why.
SELECT Id, AccountId, UserOrGroupId, AccountAccessLevel, RowCause
FROM AccountShare
WHERE AccountId = '001XXXXXXXXXXXXXXX'Common values of RowCause:
| RowCause | Meaning |
|---|---|
| `Owner` | Implicit row for the record owner |
| `Manual` | Created with the Sharing button, or by Apex using the Manual cause |
| `Team` | Created by an account or opportunity team |
| `Rule` | Created by a sharing rule |
| Custom reason | An Apex sharing reason defined on a custom object |
Role hierarchy access does not appear as a row on the record. It is resolved separately, so a manager can see a record the manager has no AccountShare row for. To see the combined result for one user, use UserRecordAccess:
SELECT RecordId, HasReadAccess, HasEditAccess, HasDeleteAccess
FROM UserRecordAccess
WHERE UserId = '005XXXXXXXXXXXXXXX'
AND RecordId = '001XXXXXXXXXXXXXXX'UserRecordAccess needs exactly one UserId and up to 200 RecordId values in the filter. It reports the final answer after every mechanism has been applied. That includes View All and Modify All.
Writing share rows from Apex
Apex can create share rows. This is how code gives one user access to a record, like the Sharing button does.
public with sharing class AccountSharer {
public static void grantRead(Id accountId, Id userId) {
AccountShare share = new AccountShare();
share.AccountId = accountId;
share.UserOrGroupId = userId;
share.AccountAccessLevel = 'Read';
share.OpportunityAccessLevel = 'None';
share.RowCause = Schema.AccountShare.RowCause.Manual;
insert share;
}
}The rules for share rows:
- Rows only add access. You cannot lower access below the org-wide default. A Read row on a Public Read/Write object is meaningless, and you cannot insert one.
- Sharing with the owner fails. The owner already has full access. Test the code with a user who is not the owner.
- The caller needs permission to share. The record's owner, a user above the owner in the hierarchy, or a user with Modify All on the object can share it. Others get an insufficient-access error.
- Manual rows disappear on owner change. Salesforce deletes Manual shares when the record's owner changes. Team and rule rows are recalculated.
- Custom objects use a custom reason. To keep rows through an owner change, define an Apex sharing reason on the custom object and use that as the
RowCause. Only Apex can create and delete rows with that reason.
Project__Share s = new Project__Share();
s.ParentId = projectId;
s.UserOrGroupId = userId;
s.AccessLevel = 'Edit';
s.RowCause = Schema.Project__Share.RowCause.Team_Access__c;
insert s;Note that the custom share table uses ParentId and AccessLevel. The standard tables use object-specific names like AccountId and AccountAccessLevel.
Common mistakes
- Declaring nothing. The behavior then depends on the caller. Declare
with sharing, orinherited sharingfor shared utilities. - Testing as an administrator. An admin with Modify All Data sees everything. Use
System.runAs()with a restricted user in tests. - Trusting a trigger to enforce sharing. Triggers run in system mode.
- Expecting a Manual row to last. An owner change removes it.
- Reading the share table as the whole answer. Hierarchy access and View All do not appear there. Use
UserRecordAccess.
Exercise
A with sharing class runs [SELECT Id FROM Contact] for a user whose profile has no Read permission on Contact. The user owns several contacts. What does the query return, and what would you add to make the class respect object permissions?
Show answer
The query returns the contacts the user owns, plus any others that sharing allows, because with sharing enforces only record-level sharing and not object permissions. To enforce Read on Contact, add WITH USER_MODE to the query. It then throws an exception for the user.
Exercise
A developer inserts an AccountShare row with RowCause = Manual and Read access for a user. Two weeks later the user loses access after an account reassignment. Why, and what could the developer do differently?
Show answer
Changing the account's owner deletes Manual share rows. A custom object can define an Apex sharing reason and use it as the RowCause, which survives owner changes. For Account, the developer should recreate the row after reassignment, for example from a trigger-called with sharing or without sharing service, or use a sharing rule or team where it fits.