Newer Version Available

This content describes an older version of this product. View Latest

CRUD and Field-Level Security (FLS)

Aura components don’t automatically enforce CRUD and FLS in an Apex controller when you reference or retrieve objects. This means that the framework continues to display records and fields for which users don’t have CRUD access and FLS visibility.

To work with Salesforce records, we recommend using Lightning Data Service, which handles sharing rules, CRUD, and field-level security for you.

Note

You must manually enforce CRUD and FLS in your Apex controllers.

For example, including the with sharing keyword in an Apex controller ensures that users see only the records they have access to in an Aura component. Additionally, you must explicitly check for isAccessible(), isCreateable(), isDeletable(), and isUpdateable() prior to performing operations on records or objects.

This example shows the recommended way to query fields on a custom expense object.

1public with sharing class ExpenseController {
2
3    // ns refers to namespace; leave out ns__ if not needed
4    // This method is vulnerable. 
5    @AuraEnabled
6    public static List<ns__Expense__c> get_UNSAFE_Expenses() {
7        return [SELECT Id, Name, ns__Amount__c, ns__Client__c, ns__Date__c, 
8            ns__Reimbursed__c, CreatedDate FROM ns__Expense__c];
9     } 
10
11    // This method is recommended.
12    @AuraEnabled
13    public static List<ns__Expense__c> getExpenses() {
14        String [] expenseAccessFields = new String [] {'Id',
15                                                       'Name',
16                                                       'ns__Amount__c',
17                                                       'ns__Client__c',
18                                                       'ns__Date__c',
19                                                       'ns__Reimbursed__c',
20                                                       'CreatedDate'
21                                                       };
22
23
24    // Obtain the field name/token map for the Expense object
25    Map<String,Schema.SObjectField> m = Schema.SObjectType.ns__Expense__c.fields.getMap();
26
27    for (String fieldToCheck : expenseAccessFields) {
28
29        // Check if the user has access to view field
30        if (!m.get(fieldToCheck).getDescribe().isAccessible()) {
31
32            // Pass error to client
33            throw new System.NoAccessException();
34        }
35    }
36 
37    // Query the object safely
38    return [SELECT Id, Name, ns__Amount__c, ns__Client__c, ns__Date__c, 
39            ns__Reimbursed__c, CreatedDate FROM ns__Expense__c];       
40    } 
41}

For more information, see Lightning Security.

Note