What is “With Sharing”? Understanding Collaborative Content Creation






What is With Sharing?


What is With Sharing?

In the world of Salesforce development, security is paramount. Every line of Apex code you write interacts with your organization’s data, and it’s crucial that this interaction respects the carefully configured permissions and sharing rules that govern who can see and do what. This is where the with sharing keyword comes into play – a fundamental mechanism for ensuring your Apex code adheres to Salesforce’s robust security model.

Understanding the Core Concept

At its heart, with sharing is an Apex keyword used in class definitions that dictates how Apex code accesses and manipulates data. When you declare an Apex class with with sharing, you’re essentially telling Salesforce: “Run this code with the same permissions as the user who is currently executing it.”

This means that any data operations performed within a with sharing class—whether it’s querying records using SOQL, performing DML operations like INSERT, UPDATE, or DELETE, or even just checking record access—will be subject to the running user’s:

  • Profiles: The fundamental set of permissions assigned to a user.
  • Role Hierarchy: How users are positioned within the organization’s reporting structure, granting access to records owned by users below them in the hierarchy.
  • Sharing Rules: Manually defined rules that grant specific users or groups access to records they wouldn’t otherwise see (e.g., public groups, roles, territories).
  • Territory Management: For organizations using this feature, it defines access based on geographic or other territories.
  • Manual Sharing: Users can sometimes manually share individual records with other users.

Key Characteristics and Behavior of With Sharing

  • Enforces User Permissions: This is the primary function. If a user doesn’t have read access to an Account record, a SOQL query within a with sharing class will simply not return that record for them. If they don’t have edit access, an UPDATE operation will fail.
  • Default Behavior for Classes: This is a crucial point for developers. By default, if you don’t explicitly specify with sharing or without sharing for an Apex class, it inherits the sharing settings of the user who invokes it. So, even without typing with sharing, many classes will behave as if they have it. However, it’s best practice to be explicit.
  • Security Best Practice: with sharing is generally the preferred approach for most Apex development. It aligns with the principle of least privilege, ensuring your code doesn’t inadvertently expose data or allow unauthorized actions.
  • Contrast with Without Sharing: The opposite of with sharing is without sharing. When you use without sharing, your Apex code runs with the highest level of system access, effectively bypassing all standard sharing rules and user permissions. This is powerful but dangerous if not used judiciously.

When Should You Use With Sharing?

The decision to use with sharing is usually straightforward and hinges on one core question: Does the logic of this code depend on what the current user can see and do?

  • User-Specific Access is Crucial: This is the most common and important scenario. If your code needs to display data tailored to the logged-in user, perform actions on records they own or have access to, or make decisions based on their role, then with sharing is the way to go.
    • Displaying a list of opportunities a salesperson can work on.
    • Updating a contact only if the user has edit access to its parent account.
    • Creating a new task related to a case, where the visibility of the case is restricted.
  • Building Reusable Components and Triggers: When developing Apex classes or triggers that will be invoked from various contexts (e.g., Visualforce pages, Lightning components, other Apex classes, or directly by users), with sharing ensures consistent and secure behavior regardless of who triggers the code.
  • Adhering to Security and Compliance: For organizations with strict data governance or compliance requirements, using with sharing is a non-negotiable part of building secure applications on the Salesforce platform.

Practical Examples

Let’s illustrate with some code snippets.

Scenario 1: Displaying Accounts Accessible by the Current User

Imagine you want to build a component that shows a user a list of accounts they can access.


public with sharing class AccountFinder {

    public List getAccessibleAccounts() {
        // This SOQL query respects the running user's access to Account records.
        // Only accounts the user has 'Read' access to will be returned.
        List userAccounts = [SELECT Id, Name, Industry FROM Account LIMIT 50];
        return userAccounts;
    }

    public void updateAccountName(Id accountId, String newName) {
        // Retrieve the account. This query is also restricted by sharing.
        Account accToUpdate = [SELECT Id, Name FROM Account WHERE Id = :accountId LIMIT 1];

        // Ensure the account was found and that the user has edit access.
        if (accToUpdate != null) {
            accToUpdate.Name = newName;
            // The 'update' DML operation is subject to the user's edit permissions on this specific account.
            update accToUpdate;
        } else {
            System.debug('Account not found or user does not have edit access to it.');
        }
    }
}
    

Explanation: In this example, getAccessibleAccounts() will only fetch accounts visible to the running user. Similarly, updateAccountName() will only succeed if the user has edit rights on the specified accountId. If not, the `update` statement will throw a DMLException.

Scenario 2: Creating a Contact Associated with an Accessible Account

Here’s how you’d create a contact, ensuring the user can access the parent account.


public with sharing class ContactCreator {

    public Contact createContactForAccount(Id accountId, String contactName, String email) {
        // First, we try to find the Account. This query respects the user's sharing rules.
        Account acc = [SELECT Id FROM Account WHERE Id = :accountId LIMIT 1];

        // If the account is accessible and exists:
        if (acc != null) {
            Contact newContact = new Contact(
                AccountId = accountId,
                FirstName = contactName.split(' ')[0],
                LastName = contactName.split(' ')[1],
                Email = email
            );
            // The 'insert' operation respects the user's permission to create Contacts
            // and implicitly their access to the parent Account.
            insert newContact;
            return newContact;
        } else {
            System.debug('Target account not found or user does not have sufficient access to it.');
            return null;
        }
    }
}
    

Explanation: Before creating the contact, the code attempts to retrieve the Account. If the user lacks access to this account, the query will return null, and the contact creation will be prevented. The insert operation also considers the user’s permissions for creating Contact records.

Technical Notes and Considerations

  • SOQL FOR VIEW and FOR UPDATE: While with sharing controls general record access, you can further refine SOQL queries. FOR VIEW (which is the default) checks read access, and FOR UPDATE checks edit access and locks the record.
  • Trigger Context: Apex triggers execute in the context of the user performing the action that fires the trigger. Therefore, with sharing in trigger handler classes is vital for maintaining security.
  • Overriding with sharing in Triggers: If a trigger handler class is declared with sharing, it will still respect user permissions even if the user is a System Administrator. To bypass sharing for a specific operation within a trigger, you might need to use without sharing (with extreme caution) or call an auxiliary method declared without sharing.
  • Test Classes: Apex test classes, by default, run as a System Administrator. This means with sharing in a test class might not accurately reflect how the code behaves for a regular user. To simulate different user profiles, use the System.runAs() method within your tests.

Troubleshooting Common Issues with With Sharing

When working with with sharing, you’ll most likely encounter permission-related errors.

  • “Insufficient Privileges” or “FIELD_CUSTOM_VALIDATION_EXCEPTION, You do not have access…” errors:
    • Problem: The running user lacks the necessary read or edit permissions on a record or a related record targeted by your Apex code.
    • Solution: Carefully review the user’s profile, role, and any relevant sharing rules for the objects involved. Ensure they have the appropriate level of access.
  • Data Not Appearing as Expected:
    • Problem: A user reports that they can’t see certain records, and your with sharing code is supposed to display them.
    • Solution: This is almost always a sharing configuration issue. Verify the user’s access settings through the Salesforce UI (e.g., the “Sharing” button on records) or by consulting with a Salesforce Administrator.
  • Trigger Logic Failing for Specific Users:
    • Problem: A trigger that uses with sharing works fine for administrators but fails for regular users.
    • Solution: Confirm that the regular users have the necessary permissions to perform the actions the trigger initiates. Alternatively, re-evaluate if the trigger *should* bypass sharing rules for certain operations (using without sharing with caution) or if the user permissions need adjustment.

Real-World Scenarios Where With Sharing Shines

With sharing is the backbone of secure custom logic in many Salesforce applications:

  • Customer Support Portals: Displaying a logged-in customer’s support cases, ensuring they only see their own tickets.
  • Salesforce Communities (Experience Cloud): Enabling customers to view and manage their account information, orders, or service requests, respecting their limited access.
  • Partner Portals: Allowing partners to view and manage opportunities or accounts relevant to their business relationship.
  • Custom Approval Workflows: Ensuring that users only interact with records they are authorized to approve or review.
  • User-Facing Data Utilities: Any tool designed for end-users to upload, edit, or view data should employ with sharing to protect data integrity and confidentiality.

Interview Relevance:

Understanding with sharing vs. without sharing is a fundamental concept for any Salesforce Developer interview. Be prepared to explain the differences, when to use each, and the security implications. You might be asked to describe a scenario where one is preferred over the other, or how to troubleshoot permission-related errors.

In conclusion, with sharing is not just a keyword; it’s a commitment to security. By consistently applying it where user-specific access is involved, you build more robust, compliant, and trustworthy applications on the Salesforce platform.

For more in-depth information, you can refer to the official Salesforce Apex documentation: