Sub topic 9
Enforcing sharing, CRUD and field-level security
This chapter assumes you can write Apex classes and SOQL, and that you know how profiles and permission sets grant object and field access. It also assumes you have a working @RestResource class like the one from the earlier chapters.
Why a REST class is not secure by default
Apex normally runs in system mode. The code ignores the caller's object permissions and field-level security (FLS). Callers authenticate as a real user, but your class can still read data that user cannot see.
Three separate controls are involved:
| Control | What it decides | How you enforce it |
|---|---|---|
| Sharing | Which records the user can see | `with sharing` on the class, or user mode |
| CRUD | Whether the user can read, create, edit or delete the object | User mode or `Security.stripInaccessible` |
| FLS | Which fields the user can read or edit | User mode or `Security.stripInaccessible` |
The with sharing keyword covers only the first control. Enforcing CRUD and FLS takes extra work.
Using user mode
User mode applies the caller's sharing, CRUD and FLS to a single operation. Add WITH USER_MODE to a query, and use as user on DML. User mode enforces sharing rules even when the class is declared without sharing. Keep with sharing anyway, so the intent is clear to readers.
If the user lacks access, Apex throws an exception. A query throws QueryException. DML throws DmlException. Catch these and return 403 instead of letting the caller see a generic 500.
@RestResource(urlMapping='/v2/Accounts/*')
global with sharing class SecureAccountService {
@HttpGet
global static Account getAccount() {
RestResponse res = RestContext.response;
String idText = RestContext.request.requestURI.substringAfterLast('/');
Id accountId;
try {
accountId = Id.valueOf(idText);
} catch (StringException e) {
res.statusCode = 400;
return null;
}
try {
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
return null;
}
return rows[0];
} catch (QueryException e) {
res.statusCode = 403;
return null;
}
}
}An empty result can mean the record does not exist or the user cannot see it. Returning 404 for both is deliberate, because it does not reveal whether a hidden record exists.
Removing fields instead of failing
User mode fails the whole operation if one field is inaccessible. Sometimes you would rather return the fields the caller may see. Security.stripInaccessible removes inaccessible fields from a list of records and reports what it removed.
@RestResource(urlMapping='/v2/AccountList/*')
global with sharing class AccountListService {
@HttpGet
global static List<Account> listAccounts() {
List<Account> rows = [
SELECT Id, Name, Industry, AnnualRevenue
FROM Account
LIMIT 50
];
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, rows);
return decision.getRecords();
}
}The query runs with sharing because of the class keyword. The stripInaccessible call then applies FLS and CRUD to the results. If the user cannot read AnnualRevenue, that field is missing from the JSON. If the user has no read access to Account at all, the call throws a NoAccessException. For writes, use AccessType.CREATABLE or AccessType.UPDATABLE.
Choose between the two approaches by what the client expects:
- Use user mode when a missing permission is an error the client should see.
- Use
stripInaccessiblewhen partial data is acceptable.
Common mistakes
- Relying on
with sharingalone and assuming FLS is covered. - Using
without sharingto "make it work" for a permission problem. Fix the permission set instead. - Returning a raw
e.getMessage()from a failed query. The message can reveal field names the caller should not know about. - Forgetting that tests run as an admin-like user by default. Use
System.runAswith a restricted user to prove the checks work.
Exercise
A caller whose profile lacks read access to Account.Industry sends a GET request to your endpoint. The query uses WITH USER_MODE and selects Industry. What happens, and how would you change the code to return the other fields instead?
Show answer
The query throws a QueryException, so the caller gets an error (a 403 if you catch it) and no data. To return the remaining fields, remove WITH USER_MODE, query with sharing enforced by the class, and pass the results through Security.stripInaccessible(AccessType.READABLE, rows). Industry is then removed from the returned records.