Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Prevent Large Data Queries in Salesforce with Transaction Security Policies
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, August 16
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Integration List
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    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

    Prevent Large Data Queries in Salesforce with Transaction Security Policies

    August 11, 2025
    By Dhanik Lal Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 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
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (117) apex best practices (5) apex code best practice (10) apex code optimization (6) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (24) salesforce (151) salesforce apex (53) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) security (4) 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

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Prevent Large Data Queries in Salesforce with Transaction Security Policies
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • 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
    Archives
    Categories
    Tags
    apex (117) apex best practices (5) apex code best practice (10) apex code optimization (6) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (24) salesforce (151) salesforce apex (53) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) security (4) 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.