Sub topic 14
FLS in Lightning components and @AuraEnabled methods
What this chapter assumes
You should know the earlier chapters' basics: that field-level security (FLS) sets Read and Edit access per field, and that Apex runs in system mode by default. You should also be able to read simple Apex and SOQL. You don't need to know Lightning Web Components (LWC) or Aura in depth. The examples are short.
The core problem: the component is not the gatekeeper
A Lightning component runs in the user's browser. It calls Apex through methods marked @AuraEnabled. Those methods run on the server in system mode, so they ignore the user's FLS unless you add enforcement.
This creates a gap. The UI may look correct, but the Apex method behind it can still return a field the user cannot read. Anyone who can call the method can see that data, including a user who calls it outside your component. Checks in JavaScript do not help, because the user controls the browser.
Enforce FLS in the Apex method. Treat every @AuraEnabled method as a public API.
Two paths: base components and your own Apex
Whether FLS is enforced depends on where the data comes from.
| Data source | FLS enforced automatically? | Notes |
|---|---|---|
| `lightning-record-form`, `lightning-record-edit-form`, `lightning-record-view-form` | Yes | These use Lightning Data Service (LDS). Fields the user cannot read are not shown, and fields they cannot edit are read-only. |
| `@wire(getRecord, ...)` and `getFieldValue` | Yes | Also built on LDS. Requesting a field the user cannot read returns an error for that field. |
| `@AuraEnabled` Apex method | No, unless you enforce it | Runs in system mode by default. |
| Apex class declared `with sharing` | Only record sharing | `with sharing` does not enforce FLS. It applies sharing rules only. |
The practical rule: prefer LDS-backed components when they meet your needs. They enforce FLS for you. Use Apex when you need logic that LDS can't provide, such as complex queries, and enforce FLS yourself.
Sharing keywords are not FLS
A common mistake is to read with sharing as "this class respects the user's permissions." It controls record visibility only. A class declared with sharing can still return a field the user has no Read access to.
public with sharing class AccountController {
// Respects record sharing, but NOT field-level security.
@AuraEnabled(cacheable=true)
public static List<Account> getAccountsUnsafe() {
return [SELECT Id, Name, AnnualRevenue FROM Account LIMIT 10];
}
}If the user cannot read AnnualRevenue, this method still returns it.
Option 1: user-mode queries (preferred)
Add WITH USER_MODE to the query. The query then enforces object permissions, FLS, and sharing rules for the running user. If the user cannot read a queried field, Apex throws a QueryException.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getTechAccounts() {
return [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
LIMIT 50
];
}
}The method fails as a whole when one field is inaccessible. That is a good fit when the component cannot work without every field. The error is raised on the server and reaches the component as an error object, so the component must handle it.
Handling errors in the component
An uncaught exception gives the user a generic message. Convert it into something readable. In Apex, catch the exception and throw an AuraHandledException with a clear message.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getTechAccounts() {
try {
return [
SELECT Id, Name, AnnualRevenue
FROM Account
WHERE Industry = 'Technology'
WITH USER_MODE
LIMIT 50
];
} catch (QueryException e) {
AuraHandledException ex = new AuraHandledException(
'You do not have access to one or more requested fields.'
);
ex.setMessage('You do not have access to one or more requested fields.');
throw ex;
}
}
}Calling setMessage matters. Without it, tests and some client paths show a generic "Script-thrown exception" text instead of your message.
The LWC side handles the result:
import { LightningElement, wire } from 'lwc';
import getTechAccounts from '@salesforce/apex/AccountController.getTechAccounts';
export default class TechAccounts extends LightningElement {
accounts;
error;
@wire(getTechAccounts)
wiredAccounts({ data, error }) {
if (data) {
this.accounts = data;
this.error = undefined;
} else if (error) {
this.error = error.body ? error.body.message : 'Unknown error';
this.accounts = undefined;
}
}
}Option 2: stripInaccessible (partial results)
Sometimes you want the method to work for everyone and just omit what a user can't see. Security.stripInaccessible removes inaccessible fields from the records instead of throwing.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
List<Account> raw = [SELECT Id, Name, AnnualRevenue FROM Account LIMIT 10];
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, raw);
return (List<Account>) decision.getRecords();
}
}Choose this when the component can render without some fields. Be aware of a side effect: a stripped field is absent from the record, not null with a value. In JavaScript, account.AnnualRevenue is undefined. Write the template to handle a missing field, or users will see blank cells without any explanation.
Option 3: describe checks
Describe methods such as isAccessible() and isUpdateable() let you check one field at a time. They give fine-grained control but are verbose and easy to forget.
public with sharing class AccountController {
@AuraEnabled
public static void updateRevenue(Id accountId, Decimal revenue) {
if (!Schema.sObjectType.Account.fields.AnnualRevenue.isUpdateable()) {
throw new AuraHandledException('You cannot edit Annual Revenue.');
}
update new Account(Id = accountId, AnnualRevenue = revenue);
}
}For most new code, user mode is shorter and harder to get wrong.
Enforcing FLS on writes
Writes need the same care as reads. A method that accepts field values from the client and saves them in system mode lets a user edit fields they should not. Use AccessLevel.USER_MODE on the DML.
public with sharing class AccountController {
@AuraEnabled
public static void saveAccount(Id accountId, Decimal revenue) {
Account acc = new Account(Id = accountId, AnnualRevenue = revenue);
Database.update(acc, AccessLevel.USER_MODE);
}
}If the user lacks Edit access to AnnualRevenue, the call throws a DmlException. Alternatively, use Security.stripInaccessible(AccessType.UPDATABLE, records) to silently drop fields the user cannot edit. Silent dropping can hide bugs, because the save appears to succeed while ignoring the value. Choose it only when that behavior is intended.
Choosing an approach
| Situation | Suggested approach |
|---|---|
| The component cannot work without every field | `WITH USER_MODE` and `AccessLevel.USER_MODE` |
| The component can render partial data | `Security.stripInaccessible` |
| You must check one field to branch your logic | Describe check |
| A standard form or record view is enough | LDS base components, no Apex |
Edge cases and common mistakes
- Dynamic SOQL.
Database.query(soql, AccessLevel.USER_MODE)enforces FLS on dynamic queries. PlainDatabase.query(soql)does not. - Cacheable methods.
@AuraEnabled(cacheable=true)results can be cached on the client. The cache is per user session, but design with care if you pass data between contexts. - Fields in relationships. User mode also checks fields reached through relationships, such as
Account.Owner.Name, and a parent field the user cannot read causes a failure. - Aggregate and filter fields. Fields in
WHEREandORDER BYclauses are also checked in user mode. A user who cannot read a field cannot filter on it. - Wrapper classes. If a method builds a custom wrapper object from query results, FLS applies only to the query. Copying a value into a wrapper does not remove it. Enforce access before building the wrapper.
- Inner logic in helper classes. Enforcement applies to the query or DML statement, not to the whole call stack. A helper class that runs its own unsafe query can leak a field even when the controller is safe.
A request flow
Exercises
Exercise
A controller class is declared with sharing. Its @AuraEnabled method runs SELECT Id, Salary__c FROM Employee__c with no other options. A user without Read access to Salary__c calls it. Does the user receive the salary, and why?
Show answer
Yes. with sharing enforces only record sharing, not FLS, and the query runs in system mode. To enforce FLS, add WITH USER_MODE to the query, or run the results through Security.stripInaccessible(AccessType.READABLE, records).
Exercise
You are building a component that shows a table of accounts. Some users cannot read AnnualRevenue, and you want the table to still load for them, without that column's values. Which approach fits, and what must the template handle?
Show answer
Use Security.stripInaccessible(AccessType.READABLE, records) and return decision.getRecords(). The stripped field is absent from each record, so the property is undefined in JavaScript. The template must handle the missing value, for example by showing a placeholder or hiding the column.
Exercise
A method takes a field value from the browser and calls update acc;. Rewrite the DML so it fails for users who cannot edit the field.
Show answer
Database.update(acc, AccessLevel.USER_MODE); This throws a DmlException when the user lacks Edit access to a field being changed.