Sub topic 9
Enforcing sharing, object and field permissions
This chapter assumes you can write an @AuraEnabled method, call it from a Lightning web component, and read basic SOQL and DML. It builds on the controller you have seen in earlier chapters and covers how to make that controller respect the running user's access.
Why the controller must enforce access
A Lightning component runs in the user's browser, so anyone can call your @AuraEnabled methods with any parameters, whatever the UI shows. Apex does not check access for you by default. Unless you ask for it, Apex runs in system context, with the access of an administrator.
A method that returns Contact records can therefore expose records or fields the user should never see. Hiding a field in the template is not a control. The server must enforce access.
Three separate controls apply to every query and DML statement:
| Control | Question it answers | Configured by |
|---|---|---|
| Object permissions (CRUD) | Can the user read, create, edit or delete this object? | Profiles, permission sets |
| Field-level security (FLS) | Can the user read or edit this field? | Profiles, permission sets |
| Sharing | Can the user see or change this particular record? | Org-wide defaults, roles, sharing rules, teams, manual shares |
The sharing keyword on a class controls only the third row. This is the most common misunderstanding in controller code, so the rest of the chapter keeps the three apart.
Sharing keywords
Every class that an @AuraEnabled method lives in should declare its sharing behavior explicitly.
with sharingenforces the running user's record access (sharing rules).without sharingignores sharing rules and returns every record.inherited sharinguses the sharing mode of the code that called the class.
A class with no keyword is a trap. When a component calls it directly as an entry point, it runs without sharing, so the user can see records beyond their access. Declare the keyword so the intent is visible in review.
public with sharing class OpportunityController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpenOpportunities(Id accountId) {
return [
SELECT Id, Name, StageName, Amount
FROM Opportunity
WHERE AccountId = :accountId AND IsClosed = false
];
}
}This class respects sharing rules, but it does not check object permissions or FLS. A user who can see an opportunity record through sharing but has no read access to Amount still receives the Amount value. In system mode, with sharing filters rows and leaves every field readable.
User mode: enforcing all three controls
Use user mode to enforce object permissions, FLS and sharing rules in one step. You add it to SOQL with WITH USER_MODE and to DML with as user.
public with sharing class OpportunityStageController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpenOpportunities(Id accountId) {
try {
return [
SELECT Id, Name, StageName, Amount
FROM Opportunity
WHERE AccountId = :accountId AND IsClosed = false
WITH USER_MODE
ORDER BY CloseDate
LIMIT 50
];
} catch (QueryException e) {
AuraHandledException ex = new AuraHandledException('You do not have access to these opportunities.');
ex.setMessage('You do not have access to these opportunities.');
throw ex;
}
}
@AuraEnabled
public static void closeOpportunity(Id opportunityId) {
try {
Opportunity opp = new Opportunity(Id = opportunityId, StageName = 'Closed Won');
update as user opp;
} catch (DmlException e) {
AuraHandledException ex = new AuraHandledException('Could not update the opportunity.');
ex.setMessage('Could not update the opportunity.');
throw ex;
}
}
}Points to note:
- User mode applies to the whole statement. If any field in the
SELECTorWHEREclause is not readable by the user, the query throws aQueryException. It does not return the record without that field. - In user mode, sharing rules are enforced even if the class is
without sharing. The statement's mode takes precedence over the class keyword. - The
AuraHandledExceptionmessage is read on the client aserror.body.message. When you construct the exception inside Apex, callsetMessageas well, becausegetMessage()otherwise returns the generic "Script-thrown exception" text. This matters most in tests. - Do not expose
e.getMessage()from a failed query blindly. It can name fields or objects the user was never meant to know about.
Dynamic SOQL has the same option. Pass AccessLevel.USER_MODE to the Database methods:
public with sharing class AccountSearchController {
@AuraEnabled(cacheable=true)
public static List<Account> search(String term) {
String pattern = '%' + String.escapeSingleQuotes(term) + '%';
Map<String, Object> binds = new Map<String, Object>{ 'pattern' => pattern };
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name LIKE :pattern LIMIT 25',
binds,
AccessLevel.USER_MODE
);
}
}The search term comes from the browser, so it is untrusted input. Passing it through a bind variable keeps it out of the query text, which prevents SOQL injection. Escaping adds a second layer, and it matters if you ever build the query string by concatenation.
Choosing an enforcement method
User mode is not the only option. You will meet the older methods in existing code.
| Method | Enforces | Behavior on a violation | Notes |
|---|---|---|---|
| `WITH USER_MODE` / `as user` | CRUD, FLS, sharing | Throws an exception | Preferred for new code. Works for SOQL and DML. |
| `WITH SECURITY_ENFORCED` | CRUD and FLS on SOQL only | Throws `QueryException` | Older. It does not enforce sharing and cannot be combined with `WITH USER_MODE`. |
| `Security.stripInaccessible` | CRUD and FLS on records you already hold | Removes inaccessible fields | Use when you want partial results instead of failure. |
| `Schema.DescribeFieldResult` checks | FLS, one field at a time | You decide | Verbose. Useful for custom logic. |
stripInaccessible fits when the user should get whatever they are allowed to see:
public with sharing class ContactViewController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
List<Contact> records = [
SELECT Id, Name, Email, Phone
FROM Contact
WHERE AccountId = :accountId
WITH SYSTEM_MODE
LIMIT 50
];
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.READABLE, records);
return decision.getRecords();
}
}Here the query itself runs in system mode, and stripInaccessible removes any field the user cannot read. In Apex, reading a removed field throws an SObjectException. In JavaScript the property is simply undefined, so templates must tolerate missing values. For writes, use AccessType.CREATABLE or AccessType.UPDATABLE before the DML. This strips fields the user may not set, which also guards against a client that sends extra data.
What the checks look like together
Common mistakes
- Relying on
with sharingalone. It hides records but not fields, and it does not check object permissions. Add user mode orstripInaccessible. - Leaving the sharing keyword off. The class runs without sharing when called from a component.
- Trusting the record Id from the client. Query it in user mode instead of updating a bare
new Opportunity(Id = ...)in system mode. Useupdate as user, as shown above, so the platform rejects an Id the user cannot edit. - Using
without sharingto "fix" a missing-record error. Find the sharing gap first. If a controller truly needs elevated access, isolate it in a smallwithout sharinghelper class, and document why it exists. - Returning whole SObjects when you need two fields. A wrapper class limits what leaves the server, and it limits the damage if an FLS check is missed. Wrapper properties are copied from the SObject by your code, so check access before you copy them.
- Forgetting the class access setting. Users also need access to the Apex class itself, through a profile or permission set, or the call fails before your code runs.
Testing the access rules
Tests run as a privileged user by default, so a test that never changes user cannot catch a missing check. Use System.runAs with a user who lacks access.
@IsTest
private class ContactControllerAccessTest {
@IsTest
static void deniesUserWithoutContactAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'noacc',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'NoAccess',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles',
ProfileId = p.Id,
UserName = 'noaccess' + System.currentTimeMillis() + '@example.com'
);
Account a = new Account(Name = 'Test Account');
insert a;
System.runAs(u) {
try {
ContactController.getContacts(a.Id);
Assert.fail('Expected a QueryException for a user without Contact access');
} catch (QueryException e) {
Assert.isTrue(true, 'Access was denied as expected');
}
}
}
}The Minimum Access - Salesforce profile grants no object permissions, so the user mode query fails. If your org does not have this profile, create a profile or permission set that omits Contact read access. System.runAs does not enforce sharing on its own. It changes the user for the code inside the block. The enforcement still comes from your query or DML statement.
Exercise
A controller class is declared with sharing and returns SELECT Id, Name, Salary__c FROM Employee__c. A user can see an employee record through a sharing rule but has no read access to Salary__c. What does the user receive, and what is the smallest change that stops the leak?
Show answer
The user receives the record including the Salary__c value, because with sharing only filters rows and does not check field-level security. Add WITH USER_MODE to the query. The query then throws a QueryException for the unreadable field. Catch it and throw an AuraHandledException with a safe message. If the user should still see the other fields, query in system mode and pass the records through Security.stripInaccessible(AccessType.READABLE, records) instead.
Exercise
Why does a test that calls a controller method directly often pass even though the method is missing its field-level security check, and how do you fix the test?
Show answer
Tests run with the permissions of the user who started them, and that user can usually read everything. The missing check is never triggered. Create a user whose profile or permission set lacks the object or field access, run the call inside System.runAs(thatUser), and assert that the expected exception is thrown or that the field is absent from the result.