Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 31, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 31, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 31, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 31, 2025

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025

      Xbox Game Pass just had its strongest content quarter ever, but can we expect this level of quality forever?

      May 31, 2025

      Gaming on a dual-screen laptop? I tried it with Lenovo’s new Yoga Book 9i for 2025 — Here’s what happened

      May 31, 2025

      We got Markdown in Notepad before GTA VI

      May 31, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Oracle Fusion new Product Management Landing Page and AI (25B)

      May 31, 2025
      Recent

      Oracle Fusion new Product Management Landing Page and AI (25B)

      May 31, 2025

      Filament Is Now Running Natively on Mobile

      May 31, 2025

      How Remix is shaking things up

      May 30, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025
      Recent

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025

      Xbox Game Pass just had its strongest content quarter ever, but can we expect this level of quality forever?

      May 31, 2025

      Gaming on a dual-screen laptop? I tried it with Lenovo’s new Yoga Book 9i for 2025 — Here’s what happened

      May 31, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Apex Security Best Practices for Salesforce Applications

    Apex Security Best Practices for Salesforce Applications

    February 3, 2025

    As businesses increasingly rely on Salesforce to manage their critical data, ensuring data security has become more important than ever. Apex, Salesforce’s proprietary programming language, runs in system mode by default, bypassing object- and field-level security. To protect sensitive data, developers need to enforce strict security measures.

    This blog will explore Apex security best practices, including enforcing sharing rules, field-level permissions, and user access enforcement to protect your Salesforce data.

    Why Apex Security is Critical for Your Salesforce Applications

    Apex’s ability to bypass security settings puts the onus on developers to implement proper Salesforce security practices. Without these protections, your Salesforce application might unintentionally expose sensitive data to unauthorized users.

    By following best practices such as enforcing sharing rules, validating inputs, and using security-enforced SOQL queries, you can significantly reduce the risk of data breaches and ensure your app adheres to the platform’s security standards.

    Enforcing Sharing Rules in Apex to Maintain Data Security

    Sharing rules are central to controlling data access in Salesforce. Apex doesn’t automatically respect these sharing rules unless explicitly instructed to do so. Here’s how to enforce them in your Apex code:

    Using with sharing in Apex Classes

    • with sharing: Ensures the current user’s sharing settings are enforced, preventing unauthorized access to records.
    • without sharing: Ignores sharing rules and is often used for administrative tasks or system-level operations where access should not be restricted.
    • inherited sharing: Inherits sharing settings from the calling class.

    Best Practice: Always use with sharing unless you explicitly need to override sharing rules for specific use cases. This ensures your code complies with Salesforce security standards.

    Example

    public class AccountHandlerWithSharing {
        public void fetchAccounts() {
            // Ensures that sharing settings are respected
            List<Account> accounts = [SELECT Id, Name FROM Account];
        }
    }
    
    public class AccountHandlerWithoutSharing {
        public void fetchAccounts() {
            // Ignores sharing settings and returns all records
            List<Account> accounts = [SELECT Id, Name FROM Account];
        }
    }
    

    Enforcing Object and Field-Level Permissions in Apex

    Apex operates in a system context by default, bypassing object- and field-level security. You must manually enforce these security measures to ensure your code respects user access rights.

    Using WITH SECURITY_ENFORCED in SOQL Queries

    The WITH SECURITY_ENFORCED keyword ensures that Salesforce performs a permission check on fields and objects in your SOQL query, ensuring that only accessible data is returned.

    Example

    List<Account> accounts = [
        SELECT Id, Name
        FROM Account
        WHERE Industry = 'Technology'
        WITH SECURITY_ENFORCED
    ];
    

    This approach guarantees that only fields and objects the current user can access are returned in your query results.

    Using the stripInaccessible Method to Filter Inaccessible Data

    Salesforce provides the stripInaccessible method, which removes inaccessible fields or relationships from query results. It also helps prevent runtime errors by ensuring no inaccessible fields are used in DML operations.

    Example

    Account acc = [SELECT Id, Name FROM Account LIMIT 1];
    Account sanitizedAcc = (Account) Security.stripInaccessible(AccessType.READABLE, acc);
    

    Using stripInaccessible ensures that any fields or relationships the user cannot access are stripped out of the Account record before any further processing.

    Apex Managed Sharing: Programmatically Share Records

    Apex Managed Sharing can be a powerful tool when you need to manage record access dynamically. This feature allows developers to programmatically share records with specific users or groups.

    Example

    public void shareRecord(Id recordId, Id userId) {
        CustomObject__Share share = new CustomObject__Share();
        share.ParentId = recordId;
        share.UserOrGroupId = userId;
        share.AccessLevel = 'Edit'; // Options: 'Read', 'Edit', or 'All'
        insert share;
    }
    

    This code lets you share a custom object record with a specific user and grant them Edit access. Apex Managed Sharing allows more flexible, dynamic record-sharing controls.

    Security Tips for Apex and Lightning Development

    Here are some critical tips for improving security in your Apex and Lightning applications:

    Avoid Hardcoding IDs

    Hardcoding Salesforce IDs, such as record IDs or profile IDs, can introduce security vulnerabilities and reduce code flexibility. Use dynamic retrieval to retrieve IDs, and consider using Custom Settings or Custom Metadata for more flexible and secure configurations.

    Validate User Inputs to Prevent Security Threats

    It is essential to sanitize all user inputs to prevent threats like SOQL injection and Cross-Site Scripting (XSS). Always use parameterized queries and escape characters where necessary.

    Use stripInaccessible in DML Operations

    To prevent processing inaccessible fields, always use the stripInaccessible method when handling records containing fields restricted by user permissions.

    Review Sharing Contexts to Ensure Data Security

    Ensure you use the correct sharing context for each class or trigger. Avoid granting unnecessary access by using with sharing for most of your classes.

    Write Test Methods to Simulate User Permissions

    Writing tests that simulate various user roles using System.runAs() is crucial to ensure your code respects sharing rules, field-level permissions, and other security settings.

    Conclusion: Enhancing Salesforce Security with Apex

    Implementing Apex security best practices is essential to protect your Salesforce data. Whether you are enforcing sharing rules, respecting field-level permissions, or programmatically managing record sharing, these practices help ensure that only authorized users can access sensitive data.

    When building your Salesforce applications, always prioritize security by:

    • Using with sharing where possible.
    • Implementing security-enforced queries.
    • Tools like stripInaccessible can be used to filter out inaccessible fields.

    By adhering to these practices, you can build secure Salesforce applications that meet business requirements and ensure data integrity and compliance.

    Further Reading on Salesforce Security

    • Salesforce Sharing and Visibility
    • Apex Security Features
    • Salesforce Best Practices for Secure Development

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleCurrying Made Simple: Demystifying JavaScript Functions
    Next Article Salesforce Security Violations: Identifying & Resolving Risks

    Related Posts

    Security

    New Apache InLong Vulnerability (CVE-2025-27522) Exposes Systems to Remote Code Execution Risks

    May 31, 2025
    Security

    New Linux Flaws Allow Password Hash Theft via Core Dumps in Ubuntu, RHEL, Fedora

    May 31, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Making Your Site Work Without JavaScript

    Web Development

    How to document multiple APIs in Laravel with Scramble

    Development

    Bill Gates would restart Microsoft as an AI-centric lab after 50 years — “Raising billions of dollars from a few sketch ideas”

    News & Updates

    Building an AI Research Agent for Essay Writing

    Machine Learning

    Highlights

    LG Display begins production of Tandem OLED for notebooks

    June 24, 2024

    The OLED display panel tech that powers the latest iPad Pro models is coming to…

    Essential Test Cases for Password and Forgot Password Functionality: A Comprehensive Guide

    July 26, 2024

    World’s First Unlimited Free AI Image Generator: Welcome Raphael AI to the Stage

    January 17, 2025

    AngularJS – Testing User Permissions/ User Access Levels

    November 12, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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