Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Friday, May 16
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Enforce Object-level and Field-level permissions in Apex

    Enforce Object-level and Field-level permissions in Apex

    Dhanik Lal SahniBy Dhanik Lal SahniFebruary 11, 20201 Comment3 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Enforce Object-level and Field-level permissions in Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Apex code is mostly run in system context so it is not considering current user’s permission. It is creating data integrity issue. Using  with sharing keywords when declaring a class enforces Sharing Rules, but not object and field-level permissions.

    In Spring 20 release some security enhancements are added to enforce object and field-level permissions.

    Using Schema Methods

    We can now use Schema.DescribeFieldResult to check current user has read, create, or update access for a field.

    For example, if we want to check that logged user has read access on PersonEmail field of the Account Object, we can enclose the SOQL query inside an if block that checks for field access using the Schema methods described above.

    if (Schema.sObjectType.Account.fields.PersonEmail.isAccessible()) {
       Contact c = [SELECT PersonEmail FROM Account WHERE Id= :Id];
    }

    Similarly we can use isCreateable, or isUpdateable method to check before inserting and updating specific fields.

    Using WITH SECURITY_ENFORCED

    WITH SECURITY_ENFORCED clause can be used in SOQL queries to enforce field and object level security permissions in Apex code. This will be applicable for subqueries and cross-object relationships as well.

    Field-level permissions are checked for all the fields that are retrieved in the SELECT clause(s) of the query. Since this clause only works inside an SOQL query, it’s only useful when we want to check for read access on a field.

    try{
        List<Account> acts = [SELECT Id, Name, Email, (SELECT LastName FROM Contacts)
            FROM Account WHERE Name like 'Universal' WITH SECURITY_ENFORCED];
    } catch(System.QueryException){
        //TODO: Handle Errors
    }

    The above query will return the Id, Email and Name of Accounts, and the LastName of the related contacts, only if the user has read access to all of these three fields. If the user doesn’t have access to at least one of these fields, the query throws a System.QueryException exception, and no results are returned.

    WITH SECURITY_ENFORCED is only applicable to field which is in select clause. If any field used in where clause then it will not check for that field.

    List<Contact> contacts = [SELECT Id, Name, FROM Contact 
                                   WHERE Image__c != null WITH SECURITY_ENFORCED];

    In above query even user does not have read access to Image__c field, it will not throw any error.

    Using stripInaccessible

    stripInaccessible method will enforce field and object level security in Apex. This method will strip fields from sObject list for which current user does not have permission.

    stripInaccessible Method Signature:

    stripInaccessible(System.AccessType accessCheckType, List<SObject> sourceRecords, [Boolean enforceRootObjectCRUD])

    System.AccessType (accessCheckType) – will show type of field level access check is being performed.

    sourceRecords – List of sObject record on which method will perform access check.

    enforceRootObjectCRUD: This indicates whether object-level access check has to be performed or not.

    Let us take example of account object. This object has custom filed Customer_Image__c.  Let us take current user does not have access to insert value in this field.

    List<Account> accts= new List<Account>{
        new Account(Name='Dhanik Sahni', Customer_Image__c='https://avatars3.githubusercontent.com/u/13779106?s=460&v=4'),
        new Account(Name='Poorvansh Sahni', Customer_Image__c='https://avatars3.githubusercontent.com/u/13779106?s=460&v=4'),
    };
    
    // Strip fields that are not creatable
    SObjectAccessDecision decision = Security.stripInaccessible(
        AccessType.CREATABLE,
        accts);
    try{
        // get field where user has access to insert
        insert decision.getRecords();
    }catch(NoAccessException e){
        system.debug(e.getMessage());
    }
    
    // Print removed fields
    System.debug(decision.getRemovedFields());

    The DML operation written above runs successfully without exceptions, but the Customer_Image__c field on the inserted records would be blank because the current user doesn’t have appropriate permissions on it.

    we can use insert decision; also but that will be insecure insertion so always use decision.getRecords() which is secure. This will return all fields where user has access to perform data insertion.

    Reference:

    https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/rn_apex_Security_stripInaccessible.htm

    apex salesforce Spring 20
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleTransaction Finalizers for Salesforce Queueable Job
    Next Article Get Food Nutrition using Spoonacular API in Lightning Web Component
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    View 1 Comment

    1 Comment

    1. Pingback: Difference Between With and Without Security in Apex

    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) code review tools (3) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex (3) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (140) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.