Ask Krrish Contact
Home
Developer & Admin
Apex Triggers Mastery Asynchronous Apex SOQL & SOSL Governor Limits Flows & Process Builder
Advanced Topics
LWC Essentials Security & Sharing Managed Packages Deployment & CI/CD Integration Patterns
Interview Prep
Practice interview questions
Resources
Sales Cloud Class Diagram
Blog AI News
Available Now
Agentforce Pricing Calculator New Debug Log Analyzer SFX Forge New SFX Grove SFX Travel Manager
Salesforce + AI
AI Agent Development Salesforce Agentforce Development Custom RAG Solutions AI + Salesforce Integration Customer Support AI Agents AI Lead Qualification AI Knowledge Base Assistant AI Workflow Automation
Salesforce work
Issue Fix Sprint Automation Sprint LWC & integrations Overflow support for partners Agentforce & AI usage review All services →
About Ask Krrish Contact

Salesforce Security and Sharing Model: Complete Guide and Interview Questions

Understand the foundational Salesforce security and sharing model to control data access effectively. This module covers profiles, permission sets, OWDs, role hierarchy, sharing rules, and programmatic sharing.

Need hands-on help?

How does record access work in Salesforce?

Salesforce record access starts from the organization-wide default (OWD), the baseline access to records a user doesn't own. The role hierarchy, sharing rules, teams, manual sharing and Apex managed sharing open access further, and restriction rules narrow it. Object permissions and field-level security from profiles and permission sets decide what users can do with those records.

  • Salesforce recommends managing permissions with permission sets and permission set groups, keeping profiles minimal.
  • Set org-wide defaults to the least access any user needs, then open access with sharing.
  • Use 'with sharing' or 'inherited sharing' on Apex classes by default.
  • Enforce field and object access with WITH USER_MODE in SOQL and AccessLevel.USER_MODE in DML; from Apex API version 67.0, database operations run in user mode by default.
  • Apex managed sharing writes rows to an object's __Share table.

1. Introduction to Salesforce Security

Salesforce's robust security and sharing model is a cornerstone of its multi-tenant architecture, designed to protect your data and ensure that users only access what they are authorized to see and do. Understanding this model is critical for administrators and developers alike to build secure and compliant applications.

Why is Security and Sharing Important?

  • Data Protection: Prevents unauthorized access to sensitive information.
  • Compliance: Helps meet regulatory and industry compliance requirements.
  • Business Logic: Ensures that business rules regarding data visibility and modification are consistently applied.
  • User Experience: Presents users with only the relevant data and functionality, reducing clutter and potential errors.
  • Scalability: Provides a scalable framework for managing access across large organizations with diverse user roles.

The Salesforce security model operates on multiple layers — from organization-wide settings down to individual record access. This module explores these layers and how they interact to control who sees what data and who can do what with it.

2. Declarative Security (Profiles & Permission Sets)

Declarative security settings control what users can do (object and field permissions) and what they can see (record access, further refined by sharing settings). Profiles and Permission Sets are the primary tools for managing these permissions.

a. Profiles

A Profile defines a user's baseline permissions and access settings. Every user in Salesforce must be assigned exactly one Profile.

  • Object Permissions: Read, Create, Edit, Delete, View All, Modify All for standard and custom objects.
  • Field-Level Security (FLS): Read and Edit access for individual fields on objects.
  • User Permissions: Access to various system functions (e.g., "Manage Users," "Modify All Data").
  • Tab Settings: Visibility of tabs (Default On, Default Off, Hidden).
  • Record Type & Page Layout Assignments: Which record types and page layouts are available to users.
  • Login Hours & IP Ranges: Restrictions on when and from where users can log in.

Limitation: Profiles are broad and apply to all users assigned to them. Customization can lead to "profile sprawl" if many unique permission combinations are needed.

b. Permission Sets

Permission Sets extend a user's functional access without changing their profile. A user can have multiple Permission Sets assigned to them.

  • Granular Permissions: Provide additional object, field, user, and tab permissions on top of the profile.
  • Additive Model: Permissions in a Permission Set are always additive — they grant access but cannot restrict access granted by a Profile.
  • Flexibility: Ideal for granting specific, temporary, or role-based permissions without creating new profiles.

Best Practice: Use a "minimum access" profile and grant additional permissions via Permission Sets. This simplifies administration and makes user access easier to manage and audit.

3. Data Access (OWD, Role Hierarchy, Sharing Rules)

While profiles and permission sets control object and field access, the sharing model determines which records a user can see and edit. This operates from the broadest settings down to the most granular.

a. Organization-Wide Defaults (OWD)

OWDs are the most restrictive baseline settings for each object — defining the default level of access users have to each other's records.

  • Private: The baseline limits access to the owner. Hierarchy access, sharing, teams, and elevated permissions can grant additional access.
  • Public Read Only: Users have baseline read access; sharing, teams, hierarchy access, and elevated permissions can grant additional access, including edit access.
  • Public Read/Write: Grants baseline read and edit access to records, subject to object permissions and applicable restrictions.
  • Public Read/Write/Transfer (Leads/Cases): Similar to Public Read/Write, but also allows transferring ownership.
  • Controlled by Parent: Access is determined by the user's access to the parent record (for master-detail relationships).

Recommendation: Choose OWDs that meet access requirements while applying least privilege. Use the hierarchy, sharing rules, teams, and programmatic sharing where additional access is needed.

b. Role Hierarchy

The Role Hierarchy can grant vertical access to records owned by users lower in the hierarchy. The access provided depends on the object and its settings; custom objects can disable Grant Access Using Hierarchies.

  • Vertical Access: Can grant access up the hierarchy, subject to object permissions and applicable settings.
  • Not for Horizontal Sharing: Does not grant access to peers at the same level.

c. Sharing Rules

Sharing Rules open up horizontal access — granting additional access to groups of users based on record ownership or field criteria. They are exceptions to OWDs and are always additive.

  • Owner-Based Sharing Rules: Share records owned by certain users (or roles/groups) with other users (or roles/groups).
  • Criteria-Based Sharing Rules: Share records that meet specific field criteria (e.g., "Opportunity Type = 'New Business'") with other users or groups.

d. Manual Sharing

Allows record owners or users with "Full Access" to share a record manually with other users, groups, or roles. Best for one-off sharing scenarios.

  • Ad-hoc Access: Provides temporary or specific access to individual records.
  • Not Scalable: Not suitable for large-scale or automated sharing requirements.

How do restriction rules differ from scoping rules?

Restriction rules narrow the records that specified users can access on supported objects. Scoping rules help users focus on a subset of records without removing access to other records.

Use a restriction rule when the requirement is to limit access to records that sharing would otherwise expose. Use a scoping rule to set a useful working context in supported features such as list views and reports. A scoping rule is not a security boundary: users can still access other records for which they have permission. Check object and feature support, and test each rule with the intended users and their existing sharing grants.

How is access managed for Experience Cloud and guest users?

Authenticated external users can receive access through sharing mechanisms supported by their licenses, including sharing sets where applicable. Guest users require separate, carefully limited access.

Sharing sets can grant eligible users access to supported records by matching their account or contact to a related account or contact on the record. Check the user's license and object support before choosing this approach. For guest users, configure the minimum object and field permissions and narrowly scoped guest user sharing rules where needed. Review the data exposed by pages, APIs, and Apex, and test the experience while unauthenticated as well as with representative external user accounts.

4. Programmatic Sharing (Apex Managed Sharing)

For complex sharing requirements that declarative tools cannot meet, Apex Managed Sharing allows developers to programmatically grant and revoke record access. Use it when sharing needs to be dynamic, based on complex calculations, or involves relationships that standard sharing rules cannot handle.

Key Concepts

  • Share Objects: Supported objects have share objects, such as AccountShare and MyCustomObject__Share. Master-detail children use their parent's sharing.
  • Access Level: Field names vary by share object. Programmatic shares generally grant Read or Edit; All is managed by the platform.
  • RowCause Field: Records the reason for a share. A custom Apex sharing reason identifies shares that the application manages separately from other grants.
  • Execution Context: Choose the class sharing declaration and database access mode deliberately. Authorize callers and satisfy the permissions required to manage the selected shares.

Apex sharing reasons are created on a custom object's detail page under Apex Sharing Reasons, and they work when the object's organization-wide default is Private or Public Read Only. The example below shares a custom Project__c object through its Project__Share table using a reason named Project_Team__c. The caller must check that the current user may grant this access before calling the service.

Apex — Custom Sharing Manager
public without sharing class ProjectSharingService {
    private static final String REASON =
        Schema.Project__Share.RowCause.Project_Team__c;

    // Grant Read access: usersByProject maps a Project Id to the users to share with.
    public static void share(Map<Id, Set<Id>> usersByProject) {
        List<Project__Share> shares = new List<Project__Share>();
        for (Id projectId : usersByProject.keySet()) {
            for (Id userId : usersByProject.get(projectId)) {
                shares.add(new Project__Share(
                    ParentId = projectId,
                    UserOrGroupId = userId,
                    AccessLevel = 'Read',
                    RowCause = REASON
                ));
            }
        }
        if (!shares.isEmpty()) {
            insert shares; // failures throw, so the caller sees them
        }
    }

    // Remove only the shares this service created for the given projects.
    public static void unshareAll(Set<Id> projectIds) {
        delete [
            SELECT Id FROM Project__Share
            WHERE ParentId IN :projectIds AND RowCause = :REASON
        ];
    }
}
  • Use system mode only for a justified operation after authorizing the caller; do not expose this service directly to untrusted users.
  • The example propagates DML failures. Handle them at the appropriate transaction boundary; for partial success, inspect every result from a bulk Database operation.
  • Account share access must meet the applicable defaults and grant additional access as required by AccountShare. A redundant or invalid grant can fail. Plan for record volume and governor limits.
  • Custom reasons keep application-managed shares distinct and preserve them when ownership changes. Review sharing recalculation and the behavior of other share types when ownership or sharing settings change.

5. Security in Apex (with sharing, FLS, CRUD)

Database operations in Apex compiled through API version 66.0 default to system mode. Starting with API version 67.0, they default to user mode, which enforces the running user's object permissions, field permissions, and sharing. Specify access modes explicitly and choose class sharing declarations deliberately so behavior is clear across API versions.

a. with sharing and without sharing

  • with sharing: Enforces record sharing for system-mode operations. It does not itself enforce object or field permissions. Use it for user-facing classes unless a specific requirement justifies another mode.
  • without sharing: Allows system-mode operations to bypass record sharing. User-mode operations still enforce the running user's sharing and permissions. Use elevated access only for an authorized purpose.
  • inherited sharing: (API v44.0+) Runs in the sharing mode of the calling class — promotes flexibility and reusability.
Apex — with sharing vs without sharing
public with sharing class AccountService {
    public static List<Account> getMyAccounts() {
        // Only returns accounts the running user can see
        return [SELECT Id, Name FROM Account WITH USER_MODE];
    }
}

public without sharing class AuditLogService {
    public static void createLog(String message) {
        // The caller must authorize this elevated operation.
        insert as system new Audit_Log__c(Message__c = message);
    }
}

b. FLS and CRUD Enforcement

A sharing declaration alone does not enforce FLS or CRUD. User-mode operations enforce these permissions as well as record access; for system-mode operations, apply the checks appropriate to the authorized task before exposing or changing data.

  • CRUD Checks (Object-level): Schema.SObjectType.Account.isAccessible(), .isCreateable(), .isUpdateable(), .isDeletable()
  • FLS Checks (Field-level): Schema.SObjectType.Account.fields.Name.isAccessible(), .isCreateable(), .isUpdateable()

c. WITH USER_MODE in SOQL

Use WITH USER_MODE to enforce object and field permissions, record sharing, and applicable restriction rules for a query. A permission failure raises an exception, so handle it at the appropriate boundary. WITH SECURITY_ENFORCED does not compile in Apex API version 67.0 and later.

Apex — WITH USER_MODE
public with sharing class SecureQueryExample {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountsSecurely() {
        // Enforces FLS and CRUD for Account.Name and Account.Industry
        return [SELECT Id, Name, Industry
                FROM Account
                WITH USER_MODE
                LIMIT 5];
    }
}

Best Practice: Declare the intended class sharing mode and specify the access mode for each database operation. Prefer user mode for user-facing work and handle permission failures; authorize and constrain any system-mode operation.

How can Apex handle inaccessible fields gracefully?

Use user-mode operations when a permission failure should stop the request. For a response that can omit inaccessible fields, Security.stripInaccessible() can remove fields the user cannot access.

Use the returned sanitized records rather than the original input, and inspect the removed fields when the application needs to explain an omission. The method can also sanitize records before DML; handle failures when required fields or object permissions are unavailable. Its default root object permission check can throw an exception. It does not enforce record sharing, so independently ensure that the records themselves are accessible. Choose the query and DML access modes deliberately and never return unsanitized data to the caller.

6. Security in LWC (Locker Service, UI API)

Lightning Web Components are built with security in mind, leveraging modern web standards and Salesforce-specific features to protect your application and data.

a. Locker Service

  • Purpose: Lightning Locker and Lightning Web Security (LWS) provide isolation between components and restrict access to resources outside their allowed scope.
  • How it Works: LWS is the default for new orgs; some older orgs use Lightning Locker. Each uses a different isolation architecture and imposes security boundaries on component code.
  • Benefits: Isolation reduces security risks, but developers must still render untrusted content safely and handle input according to its context.

b. UI API Wire Adapters

When using standard UI API wire adapters (e.g., lightning/uiRecordApi), LWC automatically enforces FLS and CRUD based on the running user's profile and permission sets.

  • For getRecord, an inaccessible field in fields causes an error; an inaccessible field in optionalFields is omitted.
  • If a user lacks CRUD access to an object, the UI API operation fails appropriately.
JavaScript — UI API Auto-Enforces FLS/CRUD
import { LightningElement, wire, api } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD     from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';

export default class AccountViewer extends LightningElement {
    @api recordId;

    @wire(getRecord, {
        recordId: '$recordId',
        fields: [NAME_FIELD],
        optionalFields: [INDUSTRY_FIELD]
    })
    account;

    get name() {
        return this.account.data ? getFieldValue(this.account.data, NAME_FIELD) : undefined;
    }
    get industry() {
        return this.account.data ? getFieldValue(this.account.data, INDUSTRY_FIELD) : undefined;
    }
    get errorMessage() {
        return this.account.error ? 'Unable to load this account.' : undefined;
    }
    // Render errorMessage when present; optional Industry may be omitted.
}

c. Imperative Apex Calls

When calling Apex imperatively from LWC, the Apex controller must enforce the intended access. Declare its sharing mode, use user-mode queries and DML where appropriate, and handle permission errors. Users also need access to the Apex class.

d. Sanitization

Validate input for its intended use. Bind values in queries, allowlist dynamic identifiers, and safely render untrusted content using context-appropriate escaping or sanitization when HTML is required. Component isolation does not replace these safeguards.

7. Security Best Practices

Implementing a robust security model requires a layered approach and consistent adherence to best practices across your Salesforce implementation.

  • Principle of Least Privilege: Grant users only the minimum access necessary to perform their job. Start restrictive and open up as needed.
  • Use Permission Sets for Access: Assign users to a minimal profile and use permission sets to grant additional permissions. Avoid creating numerous profiles.
  • Appropriate OWDs: Choose baseline access that meets requirements and applies least privilege; grant additional access selectively.
  • Secure Apex:
    • Declare a suitable sharing mode for Apex controllers handling user data.
    • Specify user mode for queries and DML that should respect the running user's access, and handle permission failures.
    • For authorized system-mode operations, enforce the required object and field permissions or apply a deliberate, narrowly scoped elevation.
    • Avoid without sharing unless absolutely necessary.
  • Secure LWC:
    • Leverage UI API wire adapters — they automatically enforce FLS/CRUD.
    • Understand Lightning Web Security or Lightning Locker and the isolation provided by the org's configuration.
    • Validate input, bind query values, allowlist dynamic identifiers, and render untrusted content safely.
  • Regular Security Audits: Periodically review your org's profiles, permission sets, and sharing rules to ensure they align with current business needs and policies.
  • Encrypt Sensitive Data: Use Salesforce Platform Encryption for highly sensitive data at rest.
  • Enforce Two-Factor Authentication (2FA): Require 2FA for all users to add an extra layer of login security.

8. Conclusion & Key Takeaways

Salesforce's security and sharing model is a sophisticated system that provides granular control over data access. From declarative tools like profiles and permission sets to programmatic options like Apex managed sharing, the platform offers a comprehensive suite of features to ensure data integrity and confidentiality.

Key Takeaways

  • Layered Security: Salesforce security operates on multiple layers — Org, Object, Field, and Record.
  • Profiles & Permission Sets: Control "what users can do." Use permission sets to extend access without profile sprawl.
  • OWD, Role Hierarchy, Sharing Rules: Control "what records users can see." OWDs are the restrictive baseline; hierarchy extends vertical access; sharing rules extend horizontal access.
  • Apex Managed Sharing: For complex, dynamic, programmatic sharing requirements beyond declarative tools.
  • Apex Security: Declare sharing and database access modes explicitly, enforce the intended permissions, and handle failures.
  • LWC Security: LWS or Lightning Locker provides isolation; UI API enforces access and reports errors for inaccessible required fields.
  • Best Practices: Apply least privilege, validate input, bind query values, render content safely, encrypt sensitive data, enforce 2FA, and conduct regular audits.

A deep understanding of the Salesforce security and sharing model is fundamental for any professional working on the platform — enabling you to build secure, scalable, and compliant applications that meet your organization's access control requirements.

Frequently asked questions

What is the difference between a profile and a permission set?

Every user has exactly one profile, while permission sets can be added and removed per user. Salesforce recommends granting permissions through permission sets and permission set groups and keeping profiles for minimal defaults.

What is the difference between with sharing and without sharing?

A class declared with sharing respects the running user's record access. Without sharing ignores sharing rules and sees all records. Inherited sharing uses the sharing mode of the calling class, and runs as with sharing when it is the entry point.

How do you enforce field-level security in Apex?

Add WITH USER_MODE to SOQL and use AccessLevel.USER_MODE for Database DML methods, which enforce object permissions, field-level security and sharing. Security.stripInaccessible removes fields the user can't access from a list of records. From Apex API version 67.0, database operations run in user mode by default; classes saved on earlier versions still run in system mode unless you ask for user mode.

What is Apex managed sharing?

Apex managed sharing grants record access in code by inserting rows into the object's share table, such as Project__Share, usually with a custom Apex sharing reason so the shares survive owner changes. It is used when the access rules are too complex for declarative sharing rules.

What are organization-wide defaults?

Organization-wide defaults (OWD) set the baseline access users have to records they don't own, such as Private, Public Read Only or Public Read/Write. Sharing rules and the role hierarchy open access from there, and restriction rules can narrow it.

Sources: Using the with sharing, without sharing and inherited sharing keywords · Enforce user mode for database operations

Get Expert Help

SFX Support — Salesforce + AI solutions. Independent: not affiliated with, endorsed by, or a partner of Salesforce, Inc. Salesforce and Agentforce are trademarks of Salesforce, Inc.