How to Manage Salesforce OAuth Tokens for Unattended Agents
Prevent silent integration failures. Learn how to generate a Salesforce OAuth token, manage the 5-token limit, and architect automated refresh loops.

A Salesforce OAuth token is the credential your unattended agent uses to call Salesforce APIs through a connected app, while scopes, policies, and user context decide how far it can reach. Getting one token in a tool like Postman is the easy part, though. Keeping that access working in production, across expiry, refresh, revocation, and permission changes, is where the real work starts.
When an agent depends on Salesforce during off-hours, an expired or revoked token can quietly stall downstream work before anyone notices. The sections below show you how to choose an OAuth flow built for machine-to-machine access, scope a connected app to least privilege, generate your first token, and handle expiry, refresh, and the 5-token limit safely.
Key Takeaways
- Use a Salesforce OAuth token through a connected app so an unattended agent can call the REST API under controlled scopes.
- Prefer JWT Bearer flow or Client Credentials flow for machine-to-machine automation, rather than the legacy Username-Password flow.
- Treat token expiry, refresh, and revocation as production behavior rather than setup details, because a token can lapse off-hours and break dependent workflows.
- Scope the API user, connected app, and OAuth policies around the minimum access the agent needs in the production environment.
- Engini provides one managed execution layer for AI agents working across Salesforce and systems of record, with scoped permissions and an audit trail built into the platform.
Defining the Salesforce OAuth Token for Agents
A Salesforce OAuth token is a credential issued after an OAuth 2.0 authorization flow. An agent then uses the access token to make Salesforce REST API calls through a connected app.
For unattended agents, the token is usually tied to an integration user or another approved execution identity. However, Salesforce still enforces that identity's native roles, permissions, object access, field rules, and API access, which is what ultimately decides how far the agent can reach.
A typical Salesforce OAuth token lifecycle includes:
- Salesforce grants an access token after a valid OAuth 2.0 flow.
- The agent sends the access token with API requests.
- The access token becomes invalid after its configured lifetime or session policy.
- The integration gets a new access token through a supported method.
- Salesforce or an admin invalidates a token, policy, app, or user session.
- The integration detects "HTTP 401 Unauthorized" responses and routes them into a controlled retry path.
Note: A valid access token proves identity, but it doesn't decide what that identity may do. This is because scopes, connected app policies, user permissions, profiles, permission sets, and destination record rules still govern every action the agent attempts.
For an agent, that means a token can authenticate cleanly, and the request can still get rejected because the user behind it can't reach the field, object, record, or API operation involved.
Choosing the Right OAuth 2.0 Flow for Automation
Salesforce supports multiple OAuth 2.0 flows, but unattended agents need flows that don't depend on a human logging in during each run. This is where the JWT Bearer and Client Credentials flows come in.
The right choice for you depends on how you want to represent the calling identity, how your security team manages certificates or secrets, and how your Salesforce organization has configured external access. For new builds, we recommend checking whether your organization uses external client apps instead of older connected app setup paths.
With that said, each flow fits a different situation, as summarized in the table below.
| Flow | Good Fit | Main Credential | Operational Concern |
|---|---|---|---|
| JWT Bearer Flow | Server-to-server access on behalf of an approved user. | Certificate and signed JSON Web Token. | Certificate rotation and user permission design. |
| Client Credentials Flow | Machine-to-machine access using app credentials. | Client ID and Client Secret. | Secret storage and app policy design. |
| Authorization Code with PKCE | Interactive user login. | User browser authorization. | Not ideal for unattended runtime execution. |
| Username-Password flow | Legacy automation patterns. | Username, password, and security token. | Avoid for unattended agents where stronger flows are available. |
The JWT Bearer Token Flow
The JWT Bearer Token Flow lets a server request a Salesforce access token by presenting a signed JSON Web Token. In this flow, your agent or backend system doesn't prompt a user to log in at runtime. Instead, it signs a JWT with a private key, and Salesforce then validates that signature against the certificate associated with the connected app.
A typical JWT Bearer Token setup includes:
- A connected app in Salesforce.
- A certificate uploaded to that connected app.
- A private key stored in your secure runtime.
- A JSON Web Token that includes the correct issuer, subject, audience, and expiry claims.
- A token request to the Salesforce OAuth token endpoint.
Tip: The JWT Bearer flow is a strong fit when you want the agent to act under a specific approved Salesforce user. Ideally, that user should be an API user or integration user with the smallest permission set the work requires.
Key and Certificate Handling
Teams often use OpenSSL to generate the private key and certificate pair for this setup. The private key stays in your secure runtime, while the certificate is uploaded to the connected app so Salesforce can verify signed JWT assertions.
The main lifecycle issue to keep in mind here has to do with certificate management. Your refresh loop may not use a refresh token, but it still depends on the private key, certificate validity, connected app policy, and user permissions. So, if any of those change, the next token request can be rejected.
The Client Credentials Flow
The Client Credentials flow lets a machine request an access token using the connected app's client credentials. It's built for machine-to-machine access: the calling application presents its Client ID (also called the Consumer Key), and its Client Secret (also called the Consumer Secret). Salesforce then issues an access token based on the connected app configuration and the execution user context.
The Client Credentials flow is useful when the app itself represents the integration rather than an interactive user session. It can reduce runtime complexity because the agent doesn't need to construct and sign a JWT assertion on each token request.
A typical Client Credentials flow design includes:
- A connected app configured for API access.
- A securely stored Client ID and Client Secret.
- A designated execution user or app context, depending on your Salesforce configuration.
- A token request to the correct My Domain OAuth endpoint.
- A rotation plan for the Client Secret.
Secret Handling and Lifecycle Risk
Here, the lifecycle risk shifts from certificate handling to secret handling. If the Client Secret rotates, expires by policy, or leaks, the integration needs a safe way to update credentials without breaking production API requests.
JWT Bearer Flow vs. Client Credentials Flow
Both the JWT Bearer flow and the Client Credentials flow can support unattended agents, but they break in different ways. JWT problems usually trace back to certificate, claim, audience, or subject issues, while Client Credentials problems usually originate from the app policy, secret rotation, or execution-user configuration you have in place.
Generating Your First Salesforce Access Token
A Salesforce access token is issued by the OAuth token endpoint once your connected app and grant type are configured correctly.
The 4 Parts of a Token Request
A basic token request has four parts:
- Endpoint: The Salesforce OAuth token endpoint for your My Domain.
- Grant type: The OAuth flow you selected.
- Client identity: The Client ID, also called the Consumer Key.
- Client proof: A signed JWT, Client Secret, or other required proof for the flow.
Request Shapes for Common Flows
For the Client Credentials flow, the request shape often looks like this:
curl https://your-domain.my.salesforce.com/services/oauth2/token \
-X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "grant_type=client_credentials" \
--data-urlencode "client_id=YOUR_CONSUMER_KEY" \
--data-urlencode "client_secret=YOUR_CONSUMER_SECRET"For the JWT Bearer flow, the request uses a signed assertion instead of a Client Secret:
curl https://your-domain.my.salesforce.com/services/oauth2/token \
-X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
--data-urlencode "assertion=YOUR_SIGNED_JWT"Other Setup Considerations
- You may see this called a Salesforce Authentication Token, but in an OAuth context the runtime credential is the access token. In other words, it differs from the Salesforce security token used in legacy username and password patterns.
- Use your My Domain endpoint where possible because it keeps the authorization path tied to the organization domain your admins control, rather than relying on a generic login endpoint.
- Start with a small check rather than a broad one. Call a harmless read endpoint first, confirm the expected user context, then try the specific REST API operation your agent needs. Also note that an approved token exchange doesn't prove the agent can create, update, or read every target record.
- Sandbox and production environments should stay separate. A sandbox-connected app is useful for testing scopes, callback settings, certificates, and token behavior, while production typically needs its own credential storage, monitoring, rotation process, and admin approval path.
Managing Token Expiry and Automated Refresh Loops
Token expiry and revocation are normal production events, and a reliable unattended agent should treat these as routine states it expects to handle on every run. Between runs, a token can expire, an admin can revoke access, or a policy can change. The next API request then returns an "HTTP 401 Unauthorized" error, and downstream work can stop unless your integration catches that response and renews the token.
For further information, make sure to check out Salesforce’s documentation on how refresh tokens behave and renew and how token limits and scopes apply to your connected app.
Building a Solid Production Token Lifecycle
Make sure to build the following into your refresh loop:
- Store access tokens, refresh tokens, private keys, and secrets in a secure secret store.
- Track token lifetime when Salesforce returns expiry data.
- Treat "HTTP 401 Unauthorized" errors as token-state signals rather than generic API errors.
- Request a new access token using the approved flow.
- Retry the original API request once upon successful token renewal.
- Use idempotency or duplicate checks before retrying create operations.
- Escalate repeated token failures to the owning team.
Designing Around the 5-Token Limit
The 5-token limit deserves your undivided attention. This is because Salesforce can limit active refresh tokens for a user and connected app combination. Once new tokens exceed this active token limit, older tokens can be revoked.
A real-world example looks something like this. A developer requests tokens against the same connected app enough times in Postman to exceed the active token limit, a CI job also authenticates, and an unattended agent gets new refresh tokens during deploy validation. The oldest refresh token tied to that user and app can then stop working, even though the production agent code did not change.
Tip: To avoid a similar situation on your end, we recommend using one approved integration user per automation boundary, keeping manual token generation away from the production-connected app, and not letting every deploy mint a new long-lived refresh token.
Renewing Your Access Safely
In addition to everything we’ve mentioned so far, a refresh loop should also avoid infinite retries. So, after one successful renewal attempt, make sure to retry the original API request. If the second call returns an "HTTP 401" error, stop and alert. At that point, the issue may be revocation, policy change, disabled user access, certificate mismatch, or connected app configuration.
For the JWT Bearer flow, renewal usually means creating a new signed JWT assertion and requesting a new access token. For the Client Credentials flow, this is done through calling the token endpoint again with valid client credentials. For the Authorization Code flow, you may need to mint a refresh token, but note that this pattern is less suited to unattended runtime agents.
Scoping Your Connected App for Least Privilege
Least privilege starts at the execution identity. Due to this, we recommend using an API user or an integration user because the execution identity should match the agent's actual job. But whatever you do, avoid using a human admin account for unattended automation.
The Least-Privilege Scoping Checklist
Make sure to cover these when you scope your connected app:
- Assign a dedicated API user or integration user.
- Grant only required object and field permissions.
- Keep profile and permission set changes auditable.
- Select only the OAuth scopes required for the API path.
- Restrict connected app access to approved users or permission sets.
- Define your refresh token policy according to the automation's risk.
- Use different connected apps for sandbox and production environment access.
- Review access after any major workflow, field, or object changes.
Setting Scopes and User Permissions
Your connected app's OAuth scopes should grant only the access the agent needs. Those scopes shape what the token can request, while user permissions still decide what the identity can do inside the organization.
Keeping Authorization Layered
Named Credentials and Auth Providers may help inside Salesforce-hosted HTTP callout patterns. With that said, they aren't a substitute for designing the external agent's credential lifecycle. If the unattended agent runs outside of Salesforce, the external runtime still needs secure storage, renewal logic, and failure handling to avoid any issues down the road.
Authorization should stay layered as well. Here is what this looks like:
- The connected app grants a path into Salesforce.
- The user context and Salesforce permission model govern what the agent can do.
- Record rules, validation rules, required fields, and API constraints still apply at execution time.
That layered model is safer than treating the access token as blanket permission and also makes failures easier to diagnose because you can separate authentication failure from authorization failure and business-rule failure.
How Engini Helps You Scope App Privileges
Scoping one connected app is manageable, but the work grows exponentially once an agent starts acting across Salesforce and other systems of record. To make matters even more complicated, each system also has its own users, scopes, and policies to keep aligned.
This is where Engini comes in. Engini is your execution layer sitting between AI agents and those systems. For any Salesforce actions routed through it, our solution can apply scoped permissions and an audit trail, while Salesforce gets to enforce its own roles and record rules.
Securing Reliable Agent Execution at Scale
The real production work is managing the Salesforce OAuth token lifecycle, long after the first token exchange succeeds. To that end, a custom JWT or Client Credentials flow is a workable in-house build that gives your team direct control over certificates, secrets, connected app policies, refresh behavior, and monitoring.
That level of control comes with a bit of upkeep, though. As the agent starts acting across Salesforce and other systems of record, each one brings its own auth model, scopes, objects, retries, and audit needs, until eventually the job shifts from getting one access token to operating a governed path across business systems.
Your next decision is how to build and run this expanded flow. If the agent only needs one narrow Salesforce read, a connected app may be enough. If it acts across Salesforce, ERP, accounting, and ordering systems, though, a managed execution layer can be the thing you need instead.
Agent gateway
Ship agents into systems you can’t afford to break
Agent gateway and workflow automation on one iPaaS core: MCP, SDK, API, or canvas, with secure auth, audit trail and tool permissions built in.
Frequently Asked Questions
Is JWT the same as OAuth?
No, they're related but not the same thing. OAuth 2.0 is an authorization framework that defines how a client gets delegated access through flows, grants, scopes, and tokens, while a JSON Web Token (JWT) is a token format. In Salesforce JWT Bearer flow, the client signs a JWT assertion and sends it to request an OAuth access token, so a JWT sits inside an OAuth flow without being OAuth itself.
Why is it a bad idea to use OAuth 2.0 for authentication?
OAuth 2.0 is built for authorization rather than authentication, so it tells an application what access a client has been granted without proving user identity the way an authentication protocol does. And so, while an authorization flow can produce an access token for API calls, your system still needs a clear execution identity, permission model, and audit trail.
For Salesforce integrations, use OAuth 2.0 to authorize API access through a connected app, but don't treat the presence of an access token as proof that the caller should perform every requested action.