Sub topic 9
Enforcing sharing, CRUD and field-level security
This chapter assumes you can write an @RestResource class with @HttpGet and @HttpPost handlers, and that you know profiles, permission sets and sharing rules at a basic level. By the end you should be able to explain what an Apex REST service enforces by default and what it does not. You should also be able to choose between user mode, stripInaccessible and manual checks.
Apex REST runs in system mode
When a client calls your service, Salesforce authenticates the caller and then runs your Apex as system mode code. System mode ignores the caller's object permissions (CRUD) and field-level security (FLS). A caller with a minimal profile can still read or write any field your code touches, unless you add the checks yourself.
Three layers of access control apply to a record:
- Object permissions (CRUD) decide whether the user can create, read, update or delete records of an object.
- Field-level security (FLS) decides whether the user can read or edit each field.
- Record sharing decides which individual records the user can see or edit, through org-wide defaults, role hierarchy, sharing rules and manual shares.
The sharing keyword on your class controls only the third layer. The first two are your responsibility.
Class access comes first
Before any of your code runs, the running user must be allowed to execute the class. Grant this through the class's Apex Class Access setting on a profile or permission set. A caller without it gets an error and the handler never executes.
The running user is the identity behind the OAuth access token. With a connected app and the authorization code flow, that is the person who logged in. With a server-to-server flow it is the integration user you configured. Give that user a dedicated permission set containing only the classes, objects and fields the integration needs. Then user mode enforces that least-privilege boundary for you.
Sharing keywords
The sharing keyword on the resource class sets whether record sharing applies to code in that class.
| Declaration | Behavior in a REST entry point |
|---|---|
| `with sharing` | Enforces the running user's record access |
| `without sharing` | Ignores sharing and returns every record |
| `inherited sharing` | Acts as `with sharing` when the class is the entry point |
| No keyword | Not safe to rely on. Classes called from your handler inherit the entry point's behavior, so declare it explicitly |
Always write with sharing on a resource class unless you have a documented reason not to. Make exceptions narrow. If one lookup must bypass sharing, put it in a small without sharing helper class and call it from the handler.
The sharing keyword does not enforce CRUD or FLS. A with sharing class can still return a field the caller is not allowed to see.
User mode: the default tool
Since API version 56.0 you can run a single SOQL query or DML statement in user mode. User mode enforces CRUD, FLS and sharing for the running user in one step. This is the first example from the plan:
@RestResource(urlMapping='/v1/Accounts/*')
global with sharing class AccountRestService {
@HttpGet
global static Account getAccount() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substringAfterLast('/');
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];
}
}WITH USER_MODE makes the query fail if the user cannot read Account or any selected field. For DML, add as user:
insert as user acc;
update as user acc;
delete as user acc;You can also use the method form, Database.insert(records, AccessLevel.USER_MODE), which takes the access level as an argument. This is useful when you also pass allOrNone and want per-record results.
User mode fails loudly. A SOQL query that selects a field the user cannot read throws a QueryException. A DML statement that violates permissions fails with an exception as well. If you do not catch it, the caller gets a generic 500 response. Catch the exception and return a status code that explains the problem, as the next chapters on error handling describe. Test which exception type your org produces and map it to a 403.
Prefer user mode over the older WITH SECURITY_ENFORCED clause. WITH SECURITY_ENFORCED checks only fields in the SELECT clause, not those in WHERE or ORDER BY, and it cannot be used for DML.
stripInaccessible: return what the user may see
User mode is all or nothing. If one selected field is hidden, the whole query fails. Sometimes you want a more forgiving API that returns the permitted fields and silently drops the rest. Security.stripInaccessible does that. It takes an AccessType and a list of records, and returns a decision object holding copies of the records with inaccessible fields removed.
@RestResource(urlMapping='/v2/Accounts/*')
global with sharing class AccountRestServiceV2 {
@HttpGet
global static Account getAccount() {
RestResponse res = RestContext.response;
String accountId = RestContext.request.requestURI.substringAfterLast('/');
List<Account> rows = [
SELECT Id, Name, Industry, AnnualRevenue
FROM Account
WHERE Id = :accountId
LIMIT 1
];
if (rows.isEmpty()) {
res.statusCode = 404;
return null;
}
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, rows);
Set<String> removed = decision.getRemovedFields().get('Account');
if (removed != null) {
res.addHeader('X-Omitted-Fields', String.join(new List<String>(removed), ','));
}
return (Account) decision.getRecords()[0];
}
}Here the query itself is not in user mode, so record sharing comes from with sharing and field access comes from stripInaccessible. A caller who cannot see AnnualRevenue still gets a 200 response without that field in the JSON. The X-Omitted-Fields header tells the client what was dropped.
The available access types are READABLE, CREATABLE, UPDATABLE and UPSERTABLE. stripInaccessible throws a NoAccessException if the user has no access to the object at all. Handle that case in your own code, usually with a 403 response.
You can also use stripInaccessible on input. Pass a record built from the request body with AccessType.CREATABLE, then call getRecords() to get a version containing only the fields the caller is allowed to write. This is useful when a client sends extra fields.
Manual checks with the describe API
The describe methods answer permission questions without running a query:
if (!Schema.sObjectType.Account.isAccessible()) {
RestContext.response.statusCode = 403;
return null;
}
Boolean canEdit = Schema.sObjectType.Account.fields.Industry.isUpdateable();Manual checks are verbose and easy to forget, so use them only when user mode and stripInaccessible do not fit. A typical case is an authorization decision that depends on a permission and is not tied to one query.
Choosing an approach
| Need | Use |
|---|---|
| Fail the request if anything is inaccessible | `WITH USER_MODE` and `as user` |
| Return the permitted subset of fields | `Security.stripInaccessible` |
| Accept only the writable part of an input record | `stripInaccessible` with `CREATABLE` or `UPDATABLE` |
| Check a permission without touching data | `Schema` describe methods |
| One controlled lookup that must ignore sharing | A small `without sharing` helper class, documented |
Common mistakes
- Relying on
with sharingalone. It does not check CRUD or FLS. The service still returns fields the caller should not see. - Using
Idfrom the URL without a query. Anupdateon an Id the user cannot see fails in user mode, but succeeds in system mode. Always run the operation withas user. - Running the integration as an administrator. User mode is only as strict as the running user. An admin integration user passes every check.
- Mixing modes in one method. If the first query uses user mode and the second does not, the second query is the weak point. Keep each handler consistent.
- Leaking details in errors. An exception message can reveal field or object names the caller should not know. Return a short message and log the details.
Testing the security boundary
Tests normally run as the user who started them, often an administrator, so they hide permission problems. Use System.runAs with a user whose profile lacks access, then assert that the service refuses the request. The profile name below exists in recent orgs, and you should confirm it in yours.
@IsTest
private class AccountRestServiceSecurityTest {
@IsTest
static void userWithoutAccountAccessIsRejected() {
Account a = new Account(Name = 'Secure Account');
insert a;
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'minacc',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Minimal',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'min.access.' + System.currentTimeMillis() + '@example.com'
);
insert u;
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/Accounts/' + a.Id;
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = new RestResponse();
System.runAs(u) {
try {
AccountRestService.getAccount();
Assert.fail('Expected the query to be rejected');
} catch (QueryException e) {
Assert.isNotNull(e.getMessage());
}
}
}
}The Assert.fail call throws an AssertException. That is not a QueryException, so the test fails if the handler returns normally. Add a second test with a user who has a permission set granting read access, and assert that the record comes back. Testing both directions proves the check blocks callers without access and does not block those with it.
Exercise
A resource class is declared with sharing. Its handler runs SELECT Id, Name, Salary__c FROM Contact WHERE Id = :contactId LIMIT 1 with no user mode clause and returns the record. A caller can see the contact record through sharing but has no read access to Salary__c. Does the caller receive the salary, and how would you fix it so the caller gets the contact without the salary field?
Show answer
Yes, the caller receives the salary. with sharing enforces only record-level sharing, and the query runs in system mode, so FLS is ignored. To return the contact without the salary, pass the results through Security.stripInaccessible(AccessType.READABLE, rows) and return getRecords(). If you would rather reject the request, add WITH USER_MODE to the query and handle the resulting QueryException with a 403 response.
Exercise
You write without sharing on a resource class and use WITH USER_MODE on every query. Which sharing rules apply to those queries, and why?
Show answer
The running user's sharing rules apply. An operation in user mode enforces sharing, CRUD and FLS for the running user, and this takes priority over the class's sharing keyword. The without sharing declaration would affect only operations that are not in user mode.
Exercise
Your integration works in production but your test passes even when the service has no security checks. What is the likely cause, and what change makes the test meaningful?
Show answer
The test runs as the administrator who started it, so every permission check passes. Wrap the handler call in System.runAs with a user who lacks the permission, such as one on the Minimum Access profile. Then assert that the handler throws or returns a 403. Add a second case with a permitted user to confirm the allowed path still works.