Introduction: The 2025 Salesforce Threat Landscape
Salesforce organisations face an evolving threat landscape — credential stuffing attacks increased 300% in 2024, supply chain compromises through AppExchange packages tripled, and AI-powered social engineering now targets Salesforce admins specifically. With the platform handling sensitive data for 150,000+ enterprises, proactive security is non-negotiable.
The 2025 security landscape demands defence-in-depth — from SOQL injection prevention in Apex code through Zero Trust architecture at the identity layer. This guide covers the complete security stack: secure development practices, authentication hardening, encryption, DevSecOps automation, and real-time threat detection with Salesforce's AI-powered security tools.
Secure Apex Development Patterns
Write injection-proof, security-enforced Apex code:
- SOQL Injection Prevention: Never concatenate user input into SOQL queries. Use bind variables (
WHERE Name = :searchTerm),String.escapeSingleQuotes()for dynamic queries, andDatabase.query()with parameterised inputs. Enable the "Require SOQL Injection Prevention" scanner in Salesforce Code Analyzer. - CRUD/FLS Enforcement: Use
WITH SECURITY_ENFORCEDin all SOQL queries,Security.stripInaccessible(AccessType.READABLE)before returning data to LWC, andSchema.SObjectType.Account.isAccessible()for dynamic object-level checks. Never usewithout sharingunless explicitly documented and approved. - DML Security: Validate all input before DML operations — check field-level create/update permissions with
Schema.SObjectField.getDescribe().isCreateable(). UseSecurity.stripInaccessible(AccessType.CREATABLE)before insert/update operations to automatically remove inaccessible fields. - Governor Limit Safety: Insecure code often emerges from governor limit workarounds — developers bypass sharing rules or skip FLS checks to reduce query complexity. Design data models and sharing architecture to support secure patterns within governor limits.
- Apex Security Scanner: Run Salesforce Code Analyzer (successor to PMD for Salesforce) on every PR — it detects SOQL injection, missing CRUD/FLS checks, hardcoded credentials, and insecure crypto usage. Configure zero-tolerance for HIGH severity findings.
Lightning Web Component Security and Locker Service
LWC security through browser-enforced isolation:
- Lightning Locker Service: Enforces Shadow DOM isolation between components — components from different namespaces cannot access each other's DOM, JavaScript scope, or event handlers. This prevents cross-component XSS attacks and ensures third-party AppExchange components can't access your data.
- DOM Sanitisation: Never use
innerHTMLin LWC — usetextContentfor text rendering andlwc:dom="manual"only when absolutely necessary with explicit sanitisation. Thelightning-formatted-rich-textcomponent safely renders HTML content with built-in XSS protection. - Lightning Data Service: Use LDS (
@wire(getRecord),lightning-record-form) instead of direct Apex calls for standard CRUD operations — LDS automatically enforces CRUD/FLS, caches data client-side, and handles sharing rules. Direct Apex calls bypass these protections unless explicitly coded. - Content Security Policy: Salesforce enforces strict CSP headers — no inline scripts, no
eval(), and third-party resources must be added to CSP Trusted Sites. This blocks most XSS attack vectors but requires using Salesforce's event system for cross-component communication. - Secure API Calls: All external API calls from LWC must go through Apex controllers — never expose API keys in client-side JavaScript. Use Named Credentials in Apex to securely manage external service authentication without exposing secrets.
OAuth 2.0 and Authentication Hardening
Implement modern authentication patterns:
- Named Credentials: Store all external service credentials in Named Credentials — they provide encrypted storage, automatic token refresh, per-user or per-org authentication, and support for OAuth 2.0, JWT Bearer, Password, and custom authentication protocols. Never store API keys in Custom Settings or Apex code.
- JWT Bearer Flow: For server-to-server integrations, use JWT Bearer Token Flow — generate tokens with RSA-256 signed assertions, short expiration (5 minutes), and certificate-based trust. This eliminates the need for stored passwords and supports automated system-to-system communication.
- Multi-Factor Authentication: Salesforce requires MFA for all direct UI logins (enforced since 2022). Implement Salesforce Authenticator, TOTP apps, or WebAuthn/FIDO2 security keys. Configure high-assurance session levels for sensitive operations — require step-up authentication for data export, user management, and configuration changes.
- Session Security: Configure session timeout policies — 2-hour timeout for standard users, 30-minute timeout for admin profiles. Enable "Lock sessions to IP address," disable "Force.com API session," and configure Login IP Ranges for all profiles to restrict geographic access.
- Connected App Controls: Configure OAuth scopes to minimum required access —
apifor data access,refresh_tokenfor long-lived sessions, and avoidfullscope. Set Token Introspection for connected apps and configure IP Relaxation to enforce IP restrictions.
Salesforce Shield and Event Monitoring
Enterprise-grade threat detection and response:
- Event Monitoring: Shield Event Monitoring captures 50+ event types — Login Events, API Events, Report Export Events, Bulk API Events, and Lightning Page View Events. Analyse events in real-time with Transaction Security Policies or batch process with Event Log Files for historical analysis.
- Transaction Security Policies: Create automated security responses — block data exports exceeding 10,000 records, require MFA for logins from new devices or countries, alert on API access outside business hours, and restrict report downloads containing sensitive fields. Policies execute in real-time with block, alert, or session-end actions.
- Threat Detection Events: Salesforce's AI-powered Threat Detection identifies credential stuffing attacks (multiple failed logins from distributed IPs), session hijacking (session ID used from different IP), and anomalous API activity (unusual query patterns or data volumes). Subscribe to platform events for real-time SIEM integration.
- Event Monitoring Analytics: Use the Event Monitoring Analytics app (prebuilt Tableau CRM dashboards) for security visualisation — login trends, API usage patterns, data access heat maps, and anomaly detection. Configure automated alerts for deviation from baseline patterns.
- SIEM Integration: Stream Event Log Files to external SIEMs (Splunk, Sumo Logic, Microsoft Sentinel) via the Event Log File Browser or Streaming API. Correlate Salesforce security events with broader infrastructure monitoring for comprehensive threat visibility.
Transform Your Publishing Workflow
Our experts can help you build scalable, API-driven publishing systems tailored to your business.
DevSecOps Pipeline Integration
Embed security into every deployment stage:
- Static Code Analysis: Run Salesforce Code Analyzer (SCA) — successor to PMD/ESLint plugins — on every pull request. SCA detects SOQL injection, missing CRUD/FLS, hardcoded secrets, insecure deserialization, and open redirect vulnerabilities. Configure CI/CD to block merges on HIGH severity findings.
- Secrets Scanning: Use tools like TruffleHog, GitLeaks, or GitHub Secret Scanning to detect accidentally committed credentials, API keys, and tokens. Configure pre-commit hooks to prevent secrets from entering the repository in the first place.
- Dependency Scanning: Audit AppExchange managed packages and third-party libraries for known vulnerabilities. Subscribe to Salesforce Security Advisory alerts and monitor CVE databases for Apex libraries. Remove or upgrade packages with known security issues.
- Security Review Automation: For AppExchange ISV partners, automate Salesforce Security Review preparation — run the Checkmarx scanner, validate CRUD/FLS enforcement across all Apex classes, ensure no hardcoded credentials, and verify CSP compliance in LWC.
- Infrastructure as Code: Define security configurations (profiles, permission sets, sharing rules, session settings) as metadata and deploy through CI/CD — prevent configuration drift and ensure security settings are version-controlled, reviewed, and auditable.
Zero Trust Architecture for Salesforce
Implement never-trust, always-verify principles:
- Identity-Centric Security: Use Salesforce Identity as the IdP with SAML 2.0 or OpenID Connect federation — centralise authentication, enforce consistent MFA policies, and enable single sign-on across Salesforce and connected applications.
- Context-Aware Access: Implement Login Flows that evaluate risk signals before granting access — device fingerprint, IP reputation, geographic location, time of day, and user behaviour patterns. Escalate to step-up MFA or block access for high-risk contexts.
- Microsegmentation: Use Permission Set Groups to create granular access boundaries — each business unit, team, or role gets precisely scoped access to objects, fields, and records. Review and recertify access quarterly to prevent permission accumulation.
- API Gateway: Route all external API traffic through API gateways (MuleSoft, Apigee) — enforce rate limiting, request validation, and threat detection before traffic reaches Salesforce. Log all API transactions for forensic analysis.
- Continuous Verification: Don't just authenticate at login — verify continuously. Monitor active sessions for anomalies, validate device posture throughout the session, and automatically terminate sessions exhibiting suspicious behaviour.
AI-Powered Threat Detection and MDS Security Services
Leverage Salesforce's AI security capabilities:
- Einstein Trust Layer: Salesforce's AI security framework ensures that customer data used in AI features is protected — data masking, zero-retention policies with LLM providers, toxicity detection, and audit logging of all AI interactions. Configure Trust Layer policies for all Einstein GPT and Copilot features.
- Anomaly Detection: Machine learning models in Event Monitoring Analytics identify unusual patterns — sudden spikes in data exports, new IP addresses accessing admin accounts, bulk record modifications outside business hours, and lateral movement between user accounts.
- Automated Response: Configure Transaction Security to automatically respond to threats — lock compromised accounts, terminate suspicious sessions, block anomalous data exports, and trigger incident response workflows with notifications to security teams via Slack or email.
- Security Centre: For multi-org enterprises, Security Centre provides a unified view of security posture across all Salesforce orgs — track MFA adoption, password policy compliance, session security settings, and API security configurations from a single dashboard.
MetaDesign Solutions delivers comprehensive Salesforce security services — from secure Apex code reviews and LWC security audits through OAuth 2.0 architecture, Shield Platform Encryption deployment, DevSecOps pipeline implementation, Zero Trust architecture design, Event Monitoring/SIEM integration, and Salesforce Security Review preparation for ISV partners.




