← Back to Security & Compliance
SEC-007 Security & Compliance 20 min read For: Solution Architects & CTOs

Salesforce Connected Apps: Security Risks Most Leaders Miss

Architecting secure OAuth authorization flows, managing integration credentials, and auditing API access scopes at scale.

VS

Vishal Sharma

Salesforce Architecture Specialist · Updated May 2026

What you will learn in this tutorial
  • Master the fundamental architecture of Salesforce Connected Apps and OAuth token management.
  • Identify critical security vulnerabilities in common OAuth flows (e.g., User-Agent vs. JWT Bearer).
  • Implement precise API scope management to enforce the principle of least privilege.
  • Establish robust governance and lifecycle management for OAuth client secrets and certificates.
  • Develop automated auditing strategies to continuously monitor Connected App permissions and usage.
  • Securely configure Connected Apps to prevent token leakage and unauthorised platform access.

1. Connected Apps and OAuth Flow Architecture

In the modern enterprise ecosystem, Salesforce rarely operates in isolation. It serves as the core system of record, constantly interacting with external systems, middleware, mobile applications, and third-party SaaS platforms. The gateway that facilitates these secure integrations is the Salesforce Connected App. A Connected App is not a container for data, nor does it run integration code; rather, it is a metadata framework that defines how an external client application interacts with Salesforce APIs. It acts as an OAuth 2.0 client definition, establishing identity and authorisation pathways. However, tech leaders and solution architects frequently misunderstand the architectural boundaries of Connected Apps, leading to severe, undetected security risks. To secure the enterprise perimeter, one must first master the mechanics of Salesforce's OAuth implementations and understand the distinct security profiles of each flow.

OAuth 2.0 is the foundational protocol used by Salesforce to authorise external clients without exposing user credentials. When an external client connects to Salesforce, it requests authorisation via one of several OAuth flows. The choice of flow is a critical security decision that determines the level of vulnerability to token interception, credential theft, and session hijacking. The most commonly deployed flows are the Authorisation Code Flow, the User-Agent Flow, the JWT Bearer Flow, and the Client Credentials Flow. Each flow has specific, non-negotiable use cases and distinct vulnerability profiles:

  • Authorisation Code Flow: Considered the gold standard for secure server-side applications. In this flow, the client application redirects the user to the Salesforce login page. Upon successful authentication, Salesforce returns a temporary authorisation code to the client via a secure redirect URI. The client application then exchanges this code for an access token and a refresh token from its secure backend server, utilising its client secret. Because the access token is requested server-to-server and the client secret is never exposed to the user's browser, the risk of interception is minimal.
  • User-Agent Flow: Designed for client-side applications, such as single-page web applications (SPAs) or mobile apps where a secure backend server is absent. In this flow, Salesforce redirects the user back to the client application and appends the access token directly to the URL fragment. This fragment is parsed by the client's browser or mobile operating system. This flow presents an exceptionally high risk profile because the access token is exposed directly in the web browser's history, referrer headers, and local memory. Malicious browser extensions or cross-site scripting (XSS) vulnerabilities can easily capture these tokens. Therefore, organisations should strictly limit or deprecate the User-Agent flow in favour of more secure alternatives, such as the Authorisation Code Flow with PKCE (Proof Key for Code Exchange).
  • JWT Bearer Flow: The industry standard for automated, non-interactive machine-to-machine integrations. In this flow, the external application uses a local private key to sign a JSON Web Token (JWT) assertion. The application posts this signed assertion to the Salesforce token endpoint. Salesforce, having the corresponding public certificate uploaded to the Connected App, verifies the signature and immediately issues an access token. The JWT flow requires no interactive login, makes no use of client secrets, and is immune to browser-based interception. It is the most robust flow for enterprise ETL tools, ESBs, and continuous integration pipelines.
  • Client Credentials Flow: A modern, simplified flow for backend integrations where the client authenticates directly using its client ID and client secret to obtain an access token on behalf of a pre-authorised integration user. While convenient, it relies heavily on the confidentiality of the client secret, which must be stored securely.

Architects must carefully evaluate these flows when establishing integrations. Selecting the wrong flow for a given environment can compromise the entire organisation's security posture, rendering even the most robust firewalls and IP restrictions ineffective.

2. Granular Scopes and Least Privilege Access

One of the most pervasive security omissions in Salesforce integration governance is the misconfiguration of OAuth scopes. Scopes define the permissions that the Connected App requests and that the user or administrator authorises. They act as a secondary authorization layer, limiting what the client application can perform, even if the authenticating user has broader system permissions. Unfortunately, many integration developers and system administrators default to assigning the full scope to their Connected Apps. This is a highly dangerous practice that violates the core security principle of least privilege.

The full scope grants the external application unrestricted access to all data and APIs, including the ability to download files, modify metadata, run reports, and execute arbitrary Apex code. If an integration with a full scope is compromised, the attacker gains absolute control over the Salesforce instance, bypassing many security boundaries. Instead of resorting to full access, architects must mandate granular scopes that align precisely with the integration's actual requirements. The following table describes the standard Salesforce OAuth scopes and their corresponding risk levels:

OAuth Scope Description Risk Profile
api Allows access to standard REST, SOAP, and Bulk APIs. Medium - Direct data access
web Allows the client to use the access token on the web. Low - Session management
refresh_token Allows a refresh token to be returned, enabling offline access. Medium - Persistent sessions
chatter_api Allows access to the Connect REST API resources (Chatter). Low - Collaboration data
full Grants access to all data and APIs, bypassing other restrictions. Critical - Absolute control

To enforce least privilege, architects must design integration-specific Connected Apps rather than sharing a single generic app across multiple external services. If an integration only needs to query customer contact information via standard REST endpoints, the Connected App should be configured with nothing more than the api and refresh_token scopes. The refresh_token scope is required to maintain a persistent connection without prompting the user to re-authenticate, but it should be accompanied by strict session policies. By isolating scopes, you ensure that a breach of one integration does not compromise others or expose administrative APIs.

3. Managing and Securing Integration Credentials

In addition to structuring secure OAuth flows, organisations must establish rigorous controls for managing and securing integration credentials. Connected Apps rely on two primary mechanisms for client authentication: client secrets and certificates. Client secrets are effectively long-term passwords generated by Salesforce for the Connected App. If a client secret is compromised, an attacker can impersonate the client application and, if scopes are loosely defined, gain unauthorised access to the Salesforce platform.

Unfortunately, client secrets are routinely mismanaged. Developers often hardcode them into application source files, commit them to public or private Git repositories, or distribute them in plaintext configuration files. To mitigate this risk, architects must establish a zero-tolerance policy for hardcoded credentials. Instead of client secrets, enterprise integrations should default to utilising certificate-based authentication, specifically through the JWT Bearer flow. In this architecture, Salesforce does not issue a client secret; instead, the external client generates an asymmetric key pair and uploads the public certificate (signed by a trusted certificate authority or self-signed for internal use) to the Salesforce Connected App metadata configuration.

When the client wishes to connect, it creates a JWT payload containing the issuer (the Connected App Client ID), the subject (the integration username), the audience (the Salesforce login or community URL), and the expiration time. The client signs this token using its locally stored private key. The private key never leaves the client's secure hosting environment and is never transmitted over the network. Salesforce receives the signed JWT assertion, validates it against the uploaded public certificate, and issues an ephemeral access token. The private key must be stored securely within an enterprise key management system, such as HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault, and injected into the client application runtime environment at execution time. This completely eliminates the threat of credentials leaking through source code repositories or system backups.

4. Connected App Policies and Network Perimeters

A major vulnerability in default Connected App configurations is the permissive nature of their access policies. By default, when a Connected App is created, the Permitted Users policy is set to "All users may self-authorise". This setting means that any user in the Salesforce organisation can initiate the OAuth flow and grant the third-party application access to their personal session and data, without administrative oversight. This is a significant compliance and security loophole, as it enables users to connect rogue external applications, personal productivity tools, or unauthorised browser extensions to the corporate Salesforce environment.

To establish proper governance, architects must switch the Permitted Users setting to "Admin approved users are pre-authorised". Once this setting is active, Salesforce blocks all self-authorisation attempts. Instead, access is strictly limited to users who have been explicitly assigned the Connected App via Profiles or Permission Sets. This allows administrators to enforce granular control, ensuring that only authorised integration service accounts or specific business personas can execute the Connected App flow. Furthermore, architects must combine pre-authorisation with strict session and network security policies:

  • IP Relaxation Policies: By default, Salesforce enforces standard user IP restrictions on Connected App logins. However, administrators can configure the Connected App to relax IP restrictions or strictly enforce them. For high-security integrations, architects should enforce corporate network IP ranges, ensuring that the integration can only connect from designated static server IPs.
  • Token Validity and Expiration: The lifetime of refresh tokens should be tightly controlled. While integrations require persistent connections, leaving refresh tokens active indefinitely creates a long-term exposure risk. Connected Apps should be configured to expire refresh tokens if they are not used within a specific period (e.g., 30 days) or to enforce immediate expiration upon use.
  • Session Timeouts: Enforce short session timeouts for the access tokens generated by the Connected App, limiting the window of opportunity for an intercepted token to be utilised by an attacker.

By defining these policies at the Connected App level, organisations can align their Salesforce integration endpoints with broader corporate security and network perimeter standards.

5. Advanced Auditing and Continuous Compliance Monitoring

Governance is not a static configuration; it requires continuous monitoring, auditing, and threat detection. Even with perfectly configured Connected Apps, security teams must regularly audit active OAuth tokens, monitor API usage patterns, and immediately revoke stale or suspicious authorizations. Salesforce provides several system objects and tools to inspect and manage Connected App sessions, but tech leaders must automate this monitoring to scale compliance effectively.

The primary object for auditing active OAuth authorizations is the OauthToken object. This object represents the active sessions and refresh tokens generated by users and integrations for various Connected Apps. Security administrators can query this object using SOQL to identify active integration sessions, track token usage counts, and isolate inactive integrations that pose an unnecessary security risk. The following SOQL query represents a robust auditing utility to locate active OAuth tokens that have not been utilised in the last 30 days:

SELECT Id, AppName, UserId, User.Name, User.Username, CreatedDate, LastUsedDate, UseCount 
FROM OauthToken 
WHERE LastUsedDate < LAST_N_DAYS:30 
ORDER BY LastUsedDate DESC

To manage this risk proactively, architects should implement automated cleanup mechanisms. The following Apex batch class demonstrates how to programmatically identify and revoke inactive OAuth tokens, ensuring that stale integration sessions are systematically pruned from the database, reducing the overall blast radius of credential exposure:

global class InactiveTokenRevocationBatch implements Database.Batchable {
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // Query OAuth tokens that have not been used in the last 30 days
        return Database.getQueryLocator([
            SELECT Id, AppName, UserId, LastUsedDate 
            FROM OauthToken 
            WHERE LastUsedDate < LAST_N_DAYS:30
        ]);
    }
    
    global void execute(Database.BatchableContext BC, List scope) {
        if (!scope.isEmpty()) {
            try {
                // Delete the inactive token records to revoke access immediately
                delete scope;
                System.debug('Successfully revoked ' + scope.size() + ' inactive OAuth tokens.');
            } catch (DmlException e) {
                System.debug('Error revoking inactive tokens: ' + e.getMessage());
            }
        }
    }
    
    global void finish(Database.BatchableContext BC) {
        // Implement completion notifications or logging as required by compliance
    }
}

In addition to programmatic token cleanup, security teams should leverage Salesforce Event Monitoring (part of Salesforce Shield) to capture detailed API logs. Every API transaction executed via a Connected App generates entries in the ApiEvent, RestApiEvent, or LightningUriEvent logs. By streaming these event logs into a centralised Security Information and Event Management (SIEM) system like Splunk, Microsoft Sentinel, or Datadog, organisations can establish real-time alerting for anomalous behaviour, such as an integration executing a sudden spike in record downloads or attempting to access unauthorised endpoints. Continuous compliance monitoring ensures that the perimeter remains secure, even as the enterprise integration landscape evolves.

Key Takeaways

  • Connected Apps serve as metadata gateways rather than data containers, defining OAuth identity and security boundaries for external applications.
  • Deprecate the highly vulnerable OAuth User-Agent flow in server-side integrations, replacing it with the secure JWT Bearer flow.
  • Enforce the principle of least privilege by avoiding the full scope and configuring granular API scopes for each unique integration.
  • Transition from client secrets to certificate-based authentication using asymmetric keys to prevent credential leakage in source code repositories.
  • Configure Connected App policies to "Admin approved users are pre-authorised" to block rogue third-party app access.
  • Implement automated token auditing and revocation using Apex batches to prune inactive OAuth sessions and minimise the attack surface.

Checkpoint: Test Your Understanding

Question 1: Which OAuth flow is highly recommended for secure, non-interactive machine-to-machine integrations in Salesforce?

A. OAuth User-Agent Flow
B. OAuth Authorisation Code Flow
C. OAuth JWT Bearer Flow
D. Username-Password Flow

Question 2: What is the primary security risk of assigning the 'full' scope to a Salesforce Connected App?

A. It increases the API request usage count by double.
B. It forces the authenticating user to reset their password.
C. It grants absolute access to all data, metadata, and APIs, bypassing standard boundary controls.
D. It automatically disables IP restrictions for the integration profile.

Question 3: How should a Salesforce administrator enforce strict control over which specific users can utilise a Connected App?

A. Leave Permitted Users as 'All users may self-authorise' and monitor logs.
B. Set Permitted Users to 'Admin approved users are pre-authorised' and assign specific Profiles or Permission Sets.
C. Change the OAuth client secret every 24 hours.
D. Encrypt all user passwords using probabilistic encryption keys.

Discussion & Feedback