Sub topic 13
Enforcing sharing and field-level security
This chapter assumes you can write inline SOQL, use bind variables, and read the QueryException that a failed query throws. It covers how to make a query respect the running user's permissions, because Apex does not do that by default.
Two separate checks, one default
Salesforce controls data access in two layers:
- Record access (sharing) decides which rows a user can see. It comes from org-wide defaults, the role hierarchy, sharing rules, and manual shares.
- Object and field permissions (CRUD and FLS) decide which objects and fields a user can read or edit. They come from profiles and permission sets.
Apex normally runs in system mode. In system mode, object permissions and field-level security (FLS) are ignored, so a query can return fields the user is not allowed to see. Record sharing is a separate setting that you control with a keyword on the class.
A query in Apex therefore has no built-in protection. A Lightning component or an @AuraEnabled method that returns query results can expose data unless you enforce permissions yourself.
Class-level sharing keywords
The sharing keyword on a class controls record visibility for the SOQL inside it.
public with sharing class AccountSelector {
public static List<Account> byIndustry(String industry) {
return [SELECT Id, Name FROM Account WHERE Industry = :industry];
}
}The three keywords behave like this:
| Keyword | Record sharing | FLS and object permissions |
|---|---|---|
| `with sharing` | Enforced for the running user | Not enforced |
| `without sharing` | Not enforced | Not enforced |
| `inherited sharing` | Uses the sharing mode of the calling class. As an entry point, it runs `with sharing`. | Not enforced |
A class with no keyword is a trap. It takes the sharing mode of its caller when called from another class, but it runs without sharing as an entry point in some contexts. Declare the keyword explicitly on every class. Use with sharing by default, and use inherited sharing for utility and selector classes that other code calls.
with sharing does nothing about FLS. A user who cannot see AnnualRevenue will still receive it from this query if the class is called in system mode for fields. You need one of the options below for that.
WITH USER_MODE
WITH USER_MODE is the recommended way to enforce everything in one clause. It applies the running user's sharing rules, object permissions, and FLS to the query, whatever sharing keyword the class has.
List<Account> accts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
];If the user cannot read AnnualRevenue, the query does not return the field with a blank value. It throws a QueryException. User mode checks every field the query touches: the SELECT list, WHERE, ORDER BY, and fields reached through relationships and subqueries.
Handle the failure explicitly in code that serves users:
public with sharing class AccountService {
public static List<Account> getAccounts() {
try {
return [
SELECT Id, Name, AnnualRevenue
FROM Account
WITH USER_MODE
LIMIT 50
];
} catch (QueryException e) {
// Thrown when the user lacks access to the object or a field
throw new AuraHandledException('You do not have access to this data.');
}
}
}Two more details:
WITH SYSTEM_MODEstates the default explicitly. Use it where code must read data the user cannot, such as a system-owned configuration object. Add a comment that says why.- User mode also exists for DML. You can write
insert as user newAccounts;or callDatabase.insert(newAccounts, AccessLevel.USER_MODE).
Dynamic SOQL and user mode
Dynamic queries do not accept the WITH USER_MODE clause as an argument. Pass an access level instead, or put the clause in the query string.
String industry = 'Technology';
List<Account> accts = Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Industry = :industry',
new Map<String, Object>{ 'industry' => industry },
AccessLevel.USER_MODE
);This combines both protections from earlier chapters: bind variables guard against injection, and user mode guards against over-reading.
Alternatives for older code or partial access
You will meet two older mechanisms in existing code bases.
WITH SECURITY_ENFORCED checks object and field access for fields in the SELECT list and throws a QueryException if one is inaccessible. It does not check fields used only in WHERE or ORDER BY, and it does not enforce record sharing. You cannot combine it with WITH USER_MODE. Prefer USER_MODE in new code.
Security.stripInaccessible takes a different approach. It removes inaccessible fields from records instead of failing the query. Use it when you want to show what the user is allowed to see and silently omit the rest.
List<Account> accts = [SELECT Id, Name, AnnualRevenue FROM Account LIMIT 50];
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, accts);
List<Account> safeAccts = (List<Account>) decision.getRecords();
Set<String> removed = decision.getRemovedFields().get('Account');
System.debug('Fields removed: ' + removed);getRemovedFields() returns a map from object name to the set of removed field names. The key is absent for an object if nothing was removed from it, so check for null before using the result. Because the removed fields are not populated on the returned records, reading one of them gives null and, for a field that was never queried, a SObjectException.
Choose among the options with this table.
| Need | Use |
|---|---|
| Enforce sharing, CRUD, and FLS, and fail if anything is blocked | `WITH USER_MODE` |
| Show only the permitted fields and drop the rest | `Security.stripInaccessible` |
| Read data the user may not see, on purpose | `WITH SYSTEM_MODE` in a `with sharing` or `inherited sharing` class |
| Maintain code that already uses it | `WITH SECURITY_ENFORCED` |
Common errors
- Assuming
with sharingprotects fields. It only filters rows. AddWITH USER_MODEfor FLS. - Forgetting that user mode throws. A single inaccessible field fails the whole query, so catch
QueryExceptionwhere users trigger the code. - Querying in system mode and returning the result to the client. Anything in the returned record is visible to the caller, even fields the page never displays.
- Testing only as an administrator. Administrators have access to nearly everything, so the permission failures never appear.
Testing permissions with System.runAs
Run the query as a user with restricted access. The test below creates its own user and its own data.
@isTest
private class AccountServiceTest {
@isTest
static void userModeQueryRunsAsRestrictedUser() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
String uniqueName = 'tester' + System.currentTimeMillis() + '@example.com';
User u = new User(
Alias = 'tester',
Email = uniqueName,
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/New_York',
Username = uniqueName
);
insert u;
insert new Account(Name = 'Owned By Admin', Industry = 'Technology');
List<Account> result;
System.runAs(u) {
result = [
SELECT Id, Name FROM Account
WHERE Name = 'Owned By Admin'
WITH USER_MODE
];
}
// With a Private org-wide default for Account, the standard user sees nothing.
// With a Public default, the user sees the record. Match the assertion to your org.
Assert.isNotNull(result);
}
}The final assertion depends on your org-wide default for Account. In a real test, assert on the exact outcome your org should produce.
Exercise
A class is declared public with sharing. A query inside it selects Id, Name, AnnualRevenue from Account without any WITH clause. The running user has no read access to AnnualRevenue. What happens, and what is the smallest change that enforces field access?
Show answer
The query succeeds and returns AnnualRevenue, because with sharing filters rows only and does not check FLS. The smallest change is to add WITH USER_MODE to the query. The query then throws a QueryException for this user, so wrap it in a try-catch where users trigger it. To return the record without the field instead of failing, query normally and pass the results through Security.stripInaccessible(AccessType.READABLE, records).
Exercise
Name two differences between WITH SECURITY_ENFORCED and WITH USER_MODE.
Show answer
WITH SECURITY_ENFORCED checks only fields in the SELECT list, while WITH USER_MODE also checks fields in WHERE and ORDER BY. WITH SECURITY_ENFORCED does not enforce record sharing, while WITH USER_MODE applies the user's sharing rules regardless of the class keyword.