For example, including the with sharing keyword in an Apex controller ensures that users see only the records they have access to in a Lightning 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 perform an operation on a custom expense object.
public with sharing class ExpenseController { // ns refers to namespace; leave out ns__ if not needed // This method is vulnerable. @AuraEnabled public static List<ns__Expense__c> get_UNSAFE_Expenses() { return [SELECT Id, Name, ns__Amount__c, ns__Client__c, ns__Date__c, ns__Reimbursed__c, CreatedDate FROM ns__Expense__c]; } // This method is recommended. @AuraEnabled public static List<ns__Expense__c> getExpenses() { String [] expenseAccessFields = new String [] {'Id', 'Name', 'ns__Amount__c', 'ns__Client__c', 'ns__Date__c', 'ns__Reimbursed__c', 'CreatedDate' }; // Obtain the field name/token map for the Expense object Map<String,Schema.SObjectField> m = Schema.SObjectType.ns__Expense__c.fields.getMap(); for (String fieldToCheck : expenseAccessFields) { // Check if the user has access to view field if (!m.get(fieldToCheck).getDescribe().isAccessible()) { // Pass error to client throw new System.NoAccessException(); // Suppress editor logs return null; } } // Query the object safely return [SELECT Id, Name, ns__Amount__c, ns__Client__c, ns__Date__c, ns__Reimbursed__c, CreatedDate FROM ns__Expense__c]; } }