Skip to content

Security Best Practices & Anti-Patterns

This page organizes security best practices and common anti-patterns by category. For CTA scenarios, demonstrating awareness of anti-patterns is just as important as knowing best practices — the board often presents scenarios with built-in anti-patterns to see if you identify and correct them.

Sharing Model Best Practices

Best Practices

PracticeWhy It Matters
Start with Private OWD for all objects, then open upYou can add access but never remove it below OWD. Starting open is irreversible without changing OWD
Design role hierarchy for data access, not HR org chartThe hierarchy controls record visibility, not reporting. An org chart hierarchy creates unnecessary sharing
Prefer criteria-based sharing rules over ownership-based when possibleCriteria rules are based on field values (stable), not record ownership (changes frequently)
Limit sharing rules to 50 per object as a practical maximumMore than 50 indicates the OWD or hierarchy design is wrong. Sharing recalculation time increases linearly
Use public groups to abstract sharing targetsGroups can be managed without modifying sharing rules. Share with “West Region Team” not individual roles
Document every sharing mechanism and its justificationThe CTA board will ask why you chose each mechanism. Future admins need to understand the design
Test sharing with different user profiles before go-liveCreate test users at each hierarchy level and verify record visibility matches requirements

Anti-Patterns

Anti-PatternRiskCorrect Approach
Setting OWD to Public Read/Write “because it’s simpler”Cannot restrict access for any user; no audit trail of access decisionsStart Private; open up with sharing rules
Mirroring the HR org chart in role hierarchyCreates deep hierarchies (10+ levels); performance degradation; unnecessary visibilityDesign for data access patterns; keep 5-7 levels max
Using manual sharing for systematic accessManual shares are deleted on ownership change; cannot be audited at scaleUse sharing rules or Apex managed sharing
Creating hundreds of sharing rulesSharing recalculation takes hours; performance degrades; impossible to auditRedesign role hierarchy or OWD
Giving View All / Modify All to bypass sharing issuesCompletely bypasses the sharing model; equivalent to admin access on that objectFix the underlying sharing design
Ignoring external OWDExternal users may see other companies’ dataSet external OWD separately (usually Private)
Not considering LDV impactPrivate OWD on 100M+ record objects causes massive share tablesEvaluate sharing set size; consider HVCP sharing sets

Identity Best Practices

Best Practices

PracticeWhy It Matters
Use the corporate IdP for all internal SSOCentralizes authentication; enables consistent MFA; simplifies offboarding
Use Federation ID for SAML user matchingDecoupled from Salesforce username; survives username changes and org migrations
Implement JIT provisioning (custom handler when possible)Eliminates manual user creation; keeps user attributes synchronized with IdP
Always enable MFA for direct login and validate IdP MFA for SSOSalesforce requires MFA; IdP-based MFA satisfies the requirement for SSO logins
Use Named Credentials for all callout authenticationKeeps credentials out of code and version control; platform manages token lifecycle
Configure Single Logout for security-sensitive environmentsPrevents orphaned sessions; user logs out everywhere when they log out anywhere
Grant minimum OAuth scopesEach scope is an attack surface; “full” scope is rarely needed
Rotate Connected App secrets and certificates on a scheduleLimits exposure window if credentials are compromised

Anti-Patterns

Anti-PatternRiskCorrect Approach
Hardcoding credentials in ApexCredentials in version control; visible to all developersUse Named Credentials
Using Username-Password OAuth flowDeprecated by Salesforce; sends credentials in plain text (over TLS, but still risky)Use JWT Bearer or Client Credentials for S2S
Not implementing Single LogoutUser logs out of IdP but Salesforce session remains activeConfigure SLO in SAML settings
Using “full” OAuth scope for all Connected AppsOver-privileged access; any compromise gives complete accessGrant minimum scopes per integration
Skipping MFA “because we have SSO”SSO without IdP MFA means single-factor authenticationVerify IdP enforces MFA or add Salesforce MFA
Multiple SSO configurations without clear routingUsers confused about which login button to use; support burdenUse Login Discovery to route users automatically
Not revoking Connected App access when integrations are decommissionedDormant access tokens remain valid; zombie integrationsAudit and revoke quarterly

Permission Model Best Practices

Best Practices

PracticeWhy It Matters
Use Minimum Access Profile patternOne baseline profile with almost no permissions; layer with Permission Sets
Create atomic Permission Sets (one function per PS)“Create Quotes” not “Sales User Everything” — enables mix-and-match
Bundle with Permission Set Groups for role assignmentGroups represent business roles; individual PS represent capabilities
Use Muting Permission Sets for exceptionsRemove specific permissions without duplicating Permission Sets
Never grant View All / Modify All unless absolutely necessaryBypasses entire sharing model; equivalent to admin access on that object
Separate UI concerns from securityPage layouts control presentation; FLS controls access. Never use page layouts as security
Audit permissions quarterlyPermission creep is real; unused Permission Sets accumulate; FLS drifts
Use Permission Set Assignment Expiration for temporary accessAuto-removes access after a specified date; prevents permanent temporary access

Anti-Patterns

Anti-PatternRiskCorrect Approach
Cloning profiles for each new roleProfile sprawl; impossible to audit; changes must be made across all clonesMinimum Access + Permission Set Groups
Managing FLS on profilesFLS changes affect all users on that profile; cannot grant different FLS to same profileManage FLS via Permission Sets
Using page layout to “hide” sensitive fieldsUsers can see hidden fields via reports, API, list viewsUse FLS to truly restrict field access
Granting System Administrator profile to integration usersFull admin access for integrations; no audit trail of what permissions are actually usedCreate integration user profile with minimum access + specific Permission Sets
Using “Modify All Data” permission as a shortcutBypasses all security; any security model becomes meaninglessGrant specific object permissions
Not distinguishing between tab visibility and object accessHiding a tab does not prevent record accessUse FLS and object permissions for security; tabs for UI convenience

Encryption Best Practices

Best Practices

PracticeWhy It Matters
Encrypt only what regulations requireEncryption has significant functionality trade-offs; over-encrypting breaks features
Do a full impact analysis before encrypting any fieldIdentify every report, query, formula, and integration that uses the field
Use deterministic encryption when searchability is requiredAllows exact-match filtering while maintaining encryption at rest
Start with Salesforce-managed keys unless regulation requires otherwiseSimplest to manage; BYOK and cache-only add operational complexity
Test extensively in sandbox before productionEncryption changes are difficult to reverse; validate all functionality
Document which fields are encrypted and whyFuture administrators need to understand the encryption rationale

Anti-Patterns

Anti-PatternRiskCorrect Approach
Encrypting everything “for extra security”Breaks search, sorting, reporting, formulas; massive functional regressionEncrypt only regulated fields
Using probabilistic when deterministic is neededUsers cannot search or filter on the field; workflow rules may breakChoose scheme based on functional requirements
Not testing encrypted field impact on reportsReports that filter or sort on encrypted fields fail silentlyTest every report that references encrypted fields
Enabling encryption without a key rotation planStale keys increase risk; compliance audits require rotation evidenceEstablish key rotation cadence before go-live
Forgetting to encrypt the search indexEncrypted field values may appear in the search index unencryptedEnable search index encryption alongside field encryption

Portal Security Best Practices

Best Practices

PracticeWhy It Matters
Set External OWD to Private for most objectsDefault assumption — external users should not see other companies’ data
Audit guest user profile quarterlyGuest user permissions creep; Salesforce tightens rules regularly
Use Sharing Sets for HVCP users instead of sharing rulesSharing Sets are optimized for high volume; sharing rules don’t apply to HVCP
Test with each external license typeDifferent licenses have different sharing behaviors; verify each one
Remove all unnecessary object permissions from guest userGuest users should have explicit opt-in access only
Never expose PII to guest usersData breach risk for unauthenticated visitors
Use “Secure guest user record access” settingEnsures records created by guest users are owned by the site’s default owner

Anti-Patterns

Anti-PatternRiskCorrect Approach
Using same OWD for internal and externalExternal users may see data from other companiesSet External OWD separately
Giving guest users API accessUnauthenticated API access enables data scrapingDisable guest API access unless specifically justified
Using Customer Community Plus when Community sufficesUnnecessary cost; adds role hierarchy complexityStart with Community; upgrade only if reporting/hierarchy needed
Not testing implicit sharing for portal usersPortal users may see parent Account data unintentionallyAudit implicit sharing paths for each external user type
Sharing too broadly via Sharing SetsRecords from one customer’s Account visible to another customerUse the narrowest possible lookup match

Programmatic Security Best Practices

Best Practices

PracticeWhy It Matters
Default to with sharing on all Apex classesEnforces the running user’s sharing model; secure by default
Use USER_MODE for SOQL and DMLEnforces CRUD + FLS + sharing comprehensively
Always use bind variables in SOQLPrevents SOQL injection; parameterized queries
Use Named Credentials for all calloutsKeeps secrets out of code; platform manages authentication
Never log sensitive data (PII, credentials, tokens)Logs are accessible to admins; may be exported
Use inherited sharing for utility classesSafe default that inherits the caller’s context
Document every without sharing usageEach bypass must be justified and reviewed

Anti-Patterns

Anti-PatternRiskCorrect Approach
No sharing keyword on Apex classesDefaults to without sharing; bypasses sharing model silentlyAlways specify with sharing or inherited sharing
Using string concatenation in SOQLSOQL injection vulnerabilityUse bind variables or String.escapeSingleQuotes()
Trusting page layout to hide fields (no FLS check in Apex)API access bypasses page layouts; users see all fieldsEnforce FLS with USER_MODE or stripInaccessible()
Storing OAuth tokens in Custom Settings/Custom MetadataVisible to all admins; in version controlUse Named Credentials
Using without sharing on controllersAll users see all records regardless of sharing modelUse with sharing on controllers; without sharing only in narrow service methods

Security Architecture Review Checklist

Use this visual checklist when reviewing any CTA scenario to ensure you have addressed every layer of the security model.

flowchart LR
    subgraph "Layer 1: Authentication"
        L1A["SSO / IdP\nConfiguration"]
        L1B["MFA\nEnforcement"]
        L1C["Login Policies\n(IP, hours)"]
    end

    subgraph "Layer 2: Authorization"
        L2A["Object CRUD\n(Profiles + PS)"]
        L2B["FLS\n(Permission Sets)"]
        L2C["Record Access\n(OWD + Sharing)"]
    end

    subgraph "Layer 3: Data Protection"
        L3A["Platform\nEncryption"]
        L3B["Data Masking\n(Formula fields)"]
        L3C["Audit Trail\n(FAT + Event Mon.)"]
    end

    subgraph "Layer 4: Integration Security"
        L4A["Named\nCredentials"]
        L4B["OAuth Flow\nSelection"]
        L4C["Token\nPolicies"]
    end

    L1A --> L2A --> L3A --> L4A
    L1B --> L2B --> L3B --> L4B
    L1C --> L2C --> L3C --> L4C

    style L1A fill:#1565c0,color:#fff
    style L1B fill:#1565c0,color:#fff
    style L1C fill:#1565c0,color:#fff
    style L2A fill:#2e7d32,color:#fff
    style L2B fill:#2e7d32,color:#fff
    style L2C fill:#2e7d32,color:#fff
    style L3A fill:#e65100,color:#fff
    style L3B fill:#e65100,color:#fff
    style L3C fill:#e65100,color:#fff
    style L4A fill:#4a148c,color:#fff
    style L4B fill:#4a148c,color:#fff
    style L4C fill:#4a148c,color:#fff

Governance Best Practices

PracticeDescriptionFrequency
Security Health CheckRun Salesforce Health Check; address all critical/high findingsMonthly
Permission auditReview all profiles, Permission Sets, and Permission Set GroupsQuarterly
Sharing rule reviewVerify all sharing rules are still needed; remove obsolete rulesQuarterly
Guest user auditReview guest user profile, sharing rules, and accessible dataQuarterly
Connected App auditReview all Connected Apps; revoke unused integrationsQuarterly
Encryption key rotationRotate encryption keys per compliance requirementsPer policy (annually minimum)
Event Monitoring reviewReview login anomalies, data export events, API patternsWeekly/Monthly
User deprovisioningVerify SSO-deprovisioned users are deactivated in SalesforceAutomated or weekly

Sources