Sub topic 3
Enforcing Field-Level Security in Apex and Lightning
Assume you know Salesforce objects, fields, records, users, and basic Apex and SOQL. Field-level security (FLS) controls field Read and Edit access, but Apex runs in system mode by default and can bypass FLS.
User-mode SOQL and DML
Use WITH USER_MODE for SOQL and AccessLevel.USER_MODE for Database operations. These options enforce the running user’s object permissions, FLS, and sharing rules.
List<Account> accounts = [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
];
Account accountRecord = new Account(Name = 'Acme');
Database.insert(accountRecord, AccessLevel.USER_MODE);A user-mode query throws an exception when the user cannot read a selected field. User-mode DML rejects fields or objects the user cannot create or edit.
Removing inaccessible fields
Security.stripInaccessible removes fields the user cannot access instead of failing the entire response. This is useful when a controller returns records to a client.
List<Account> raw = [SELECT Id, Name, AnnualRevenue FROM Account LIMIT 10];
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, raw);
List<Account> safe = (List<Account>) decision.getRecords();Describe checks
Describe methods support fine-grained decisions. Check isAccessible() before reading and isUpdateable() before assigning a value. This approach can become repetitive because every sensitive field needs a check.
if (Schema.sObjectType.Account.fields.AnnualRevenue.isUpdateable()) {
accountRecord.AnnualRevenue = 2000000;
}Lightning and `@AuraEnabled`
Lightning Data Service and UI API respect FLS. An @AuraEnabled Apex method does not automatically do so. Enforce FLS inside the method with user-mode queries or DML, or sanitize results with stripInaccessible.
Testing access
Create a restricted user, assign only the intended permission set, and call the code inside System.runAs. Test the actual user-mode operation and assert that restricted fields fail or are removed.
Metadata deployment
FLS is represented by fieldPermissions in a permission set or profile.
<fieldPermissions>
<editable>true</editable>
<field>Account.Internal_Notes__c</field>
<readable>true</readable>
</fieldPermissions>Deploy permission sets and permission set groups as metadata. Permission set groups combine permissions; they do not reduce access granted elsewhere.
Least-privilege design
Start fields as hidden and grant access only to users who need it. Review permission assignments regularly, audit sensitive fields, and keep FLS changes in source control.
Exercise
Which option should return partial records while removing unreadable fields?
Show answer
Use Security.stripInaccessible(AccessType.READABLE, records).