Newer Version Available
Enforcing Object and Field Permissions
Apex generally runs in system context; that is, the current user's permissions and field-level security aren’t taken into account during code execution. Sharing rules, however, are not always bypassed: the class must be declared with the without sharing keyword in order to ensure that sharing rules are not enforced. Apex code that is executed with the executeAnonymous call and Connect in Apex always execute using the sharing rules of the current user. For more information on executeAnonymous, see Anonymous Blocks.
Although Apex doesn't enforce object-level and field-level permissions by default, you can enforce these permissions in your SOQL queries by using WITH SECURITY_ENFORCED. For more information, see Filter SOQL Queries Using WITH SECURITY_ENFORCED.
You can also enforce object-level and field-level permissions in your code by explicitly calling the sObject describe result methods (of Schema.DescribeSObjectResult) and the field describe result methods (of Schema.DescribeFieldResult) that check the current user's access permission levels. In this way, you can verify if the current user has the necessary permissions, and only if he or she has sufficient permissions, you can then perform a specific DML operation or a query.
For example, you can call the isAccessible, isCreateable, or isUpdateable methods of Schema.DescribeSObjectResult to verify whether the current user has read, create, or update access to an sObject, respectively. Similarly, Schema.DescribeFieldResult exposes these access control methods that you can call to check the current user's read, create, or update access for a field. In addition, you can call the isDeletable method provided by Schema.DescribeSObjectResult to check if the current user has permission to delete a specific sObject.
These are some examples of how to call the access control methods.
1if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) {
2 // Update contact phone number
3}1if (Schema.sObjectType.Contact.fields.Email.isCreateable()) {
2 // Create new contact
3}1if (Schema.sObjectType.Contact.fields.Email.isAccessible()) {
2 Contact c = [SELECT Email FROM Contact WHERE Id= :Id];
3}1if (Schema.sObjectType.Contact.isDeletable()) {
2 // Delete contact
3}Sharing rules are distinct from object-level and field-level permissions. They can coexist. If sharing rules are defined in Salesforce, you can enforce them at the class level by declaring the class with the with sharing keyword. For more information, see Using the with sharing, without sharing, and inherited sharing Keywords. If you call the sObject describe result and field describe result access control methods, the verification of object and field-level permissions is performed in addition to the sharing rules that are in effect. Sometimes, the access level granted by a sharing rule could conflict with an object-level or field-level permission.