In Salesforce, while we do development, ensuring data security is important, and we can do that using the CRUD feature. CRUD permissions allow us to define what a user can do with different data types. Validating these permissions before performing SOQL or DML operations helps maintain the security of the org application and protects sensitive data.
In this Salesforce tutorial, I will explain how to validate the CRUD permission before SOQL/DML operations in Salesforce.
CRUD permission validation in Salesforce Apex
Salesforce enforces CRUD and FLS (Field Level Security) at the platform level for declarative tools like standard UI and reports. Not validating the CRUD permissions can lead to unauthorized access to data and create data security issues.
Methods for CRUD Validation in Salesforce Apex
Salesforce provides methods in the Schema.DescribeSObjectResult and Schema.DescribeFieldResult classes to check CRUD and FLS permissions. Below are the methods to validate the CRUD permission in Salesforce.
- isCreateable(): This method checks permission to create records.
- isAccessible(): It checks if the user can read records.
- isUpdateable(): Checks if the user has permission to update records.
- isDeletable(): Checks if the user has permission to delete records.
Validate Read Permission Before SOQL Query
Validate the user’s read permission before the SOQL query.
Apex Class:
public class getAccounts {
public void fetchAccounts() {
if (!Schema.SObjectType.Account.isAccessible()) {
System.debug('Access to Account records is denied.');
throw new SecurityException('You do not have permission to access Account records.');
}
System.debug('Access to Account records is granted.');
List<Account> accounts = [SELECT Id, Name FROM Account];
System.debug('Fetched Accounts: ' + accounts);
}
}
Calling the class method fetchAccounts to show the output :
getAccounts ga = new getAccounts();
ga.fetchAccounts();
Output:
