Ask Krrish Contact Us
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
Available Now
Debug Log Analyzer
Coming Soon
Org Comparator Soon
Resources About Ask Krrish Contact Us

Salesforce Security & Sharing Interview Questions — SFX Support

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?

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: Only the record owner and users higher in the role hierarchy can view, edit, and report on those records.
  • Public Read Only: All users can view records, but only the owner and higher-role users can edit them.
  • Public Read/Write: All users can view and edit all records.
  • 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: Always set OWDs to the most restrictive level possible, then open up access using role hierarchy, sharing rules, and Apex managed sharing.

b. Role Hierarchy

The Role Hierarchy opens up vertical access. Users at any given role level can automatically view, edit, and report on all records owned by users below them in the hierarchy, regardless of OWD settings.

  • Vertical Access: Grants access up the hierarchy (managers can see subordinates' records).
  • 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.

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: Every standard or custom object has an associated Share object (e.g., AccountShare, MyCustomObject__Share) that stores explicit sharing records.
  • AccessLevel Field: Defines the level of access granted (Read, Edit, All).
  • RowCause Field: Indicates why a user has access. For Apex Managed Sharing, always use a custom RowCause with Type = Apex.
  • without sharing: Apex classes that create/update/delete share objects should generally run without sharing so they can modify sharing records regardless of the running user's own access.
Apex — Custom Sharing Manager
public class CustomSharingManager {

    // Custom RowCause defined in Setup → Sharing Settings → Your Object → New Sharing Reason
    public static final Schema.SObjectRowCause CustomShareReason =
        Schema.SObjectRowCause.MyCustomShareReason__c;

    public static void shareAccountWithUser(Id accountId, Id userId, String accessLevel) {
        if (!Schema.sObjectType.AccountShare.isCreateable()) {
            throw new AuraHandledException('Insufficient permissions to create AccountShare records.');
        }

        AccountShare accShare = new AccountShare();
        accShare.ParentId      = accountId;
        accShare.UserOrGroupId = userId;
        accShare.AccessLevel   = accessLevel;   // 'Read', 'Edit', or 'All'
        accShare.RowCause      = CustomShareReason;

        try {
            insert accShare;
        } catch (DmlException e) {
            System.debug('Error sharing account: ' + e.getMessage());
        }
    }

    public static void removeAccountSharing(Id accountId, Id userId) {
        List<AccountShare> sharesToDelete = [
            SELECT Id FROM AccountShare
            WHERE ParentId      = :accountId
            AND   UserOrGroupId = :userId
            AND   RowCause      = :CustomShareReason
        ];

        if (!sharesToDelete.isEmpty()) {
            try {
                delete sharesToDelete;
            } catch (DmlException e) {
                System.debug('Error removing sharing: ' + e.getMessage());
            }
        }
    }
}
  • Apex Managed Sharing is complex — use it judiciously.
  • Always define a custom RowCause to distinguish programmatic shares from other sharing types.
  • Be mindful of governor limits when performing DML on share objects at scale.

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

Apex code runs in system context by default — it has access to all objects and fields regardless of the running user's permissions. To enforce security, developers must explicitly implement these mechanisms.

a. with sharing and without sharing

  • with sharing: Enforces the running user's sharing rules. Queries only return records the user can access; DML fails if the user lacks permission. Recommended default for most Apex classes.
  • without sharing: Bypasses sharing rules entirely — runs in system context. Use with extreme caution, only for system-level operations like audit logging where user sharing should not block the operation.
  • 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];
    }
}

public without sharing class AuditLogService {
    public static void createLog(String message) {
        // System-level operation — bypasses sharing (use with caution)
        insert new Audit_Log__c(Message__c = message);
    }
}

b. FLS and CRUD Enforcement

Even with with sharing, Apex does not automatically enforce FLS or CRUD. You must explicitly check these before DML operations or displaying sensitive 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 SECURITY_ENFORCED in SOQL

(API v45.0+) Automatically enforces object and field-level security for the query. If the user lacks access to any object or field in the query, an error is thrown. Highly recommended for all queries.

Apex — WITH SECURITY_ENFORCED
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 SECURITY_ENFORCED
                LIMIT 5];
    }
}

Best Practice: Always use with sharing for Apex classes handling user data. Use WITH SECURITY_ENFORCED in SOQL/SOSL queries. Explicitly check CRUD and FLS before DML operations.

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: Isolates Lightning components from each other and from the global DOM. Prevents components from accessing or manipulating resources they don't own.
  • How it Works: Wraps components in a secure container with a strict API for interaction. All LWC components automatically run within Locker Service.
  • Benefits: Prevents XSS attacks, protects sensitive data, and ensures safe component interoperability.

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.

  • If a user lacks FLS access to a field, that field's data is not returned.
  • 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, INDUSTRY_FIELD] })
    account;

    get name()     { return getFieldValue(this.account.data, NAME_FIELD); }
    get industry() { return getFieldValue(this.account.data, INDUSTRY_FIELD); }

    // If user lacks FLS for Name/Industry → those fields return null
    // If user lacks Read access to Account → account.data is undefined
}

c. Imperative Apex Calls

When calling Apex imperatively from LWC, security enforcement shifts to the Apex controller. Ensure your Apex methods use with sharing and WITH SECURITY_ENFORCED to respect the running user's permissions.

d. Sanitization

Always sanitize user-provided input before rendering it in the DOM or using it in queries/DML. While LWC and Locker Service provide protection, explicit sanitization is a best practice to prevent XSS vulnerabilities.

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.
  • Most Restrictive OWDs: Set OWDs to the most restrictive level (Private), then use role hierarchy, sharing rules, and Apex managed sharing to open up access selectively.
  • Secure Apex:
    • Always use public with sharing class for Apex controllers handling user data.
    • Use WITH SECURITY_ENFORCED in all SOQL/SOSL queries.
    • Perform explicit FLS and CRUD checks before DML operations.
    • Avoid without sharing unless absolutely necessary.
  • Secure LWC:
    • Leverage UI API wire adapters — they automatically enforce FLS/CRUD.
    • Understand Locker Service and how it isolates your components.
    • Sanitize all user-provided input before rendering or using in data operations.
  • 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: Use with sharing, WITH SECURITY_ENFORCED, and explicit FLS/CRUD checks.
  • LWC Security: Benefits from Locker Service isolation and UI API's automatic FLS/CRUD enforcement.
  • Best Practices: Least privilege, sanitize input, 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.

Get Expert Help

Independent community initiative. Not affiliated with Salesforce.com, Inc.