Sub topic 18
Security practices for tokens and secrets
This chapter assumes you have read the earlier chapters on the web server, JWT bearer, and client credentials flows. You should know what a connected app is, what the consumer key and secret are, and how access tokens, refresh tokens, and the instance_url fit together. Here the focus is on keeping those values safe.
What you are protecting
Each flow produces or uses a different set of sensitive values. Knowing which is which tells you how much care each one needs.
| Value | Where it comes from | Risk if leaked | Lifetime |
|---|---|---|---|
| Consumer key | Connected app | Low alone. It identifies the app and appears in browser URLs. | Until the app is changed |
| Consumer secret | Connected app | High. With the key, it can request tokens in the web server and client credentials flows. | Until rotated |
| Private key (`server.key`) | You generate it | Critical. Anyone holding it can sign assertions for the pre-authorized user. | Until you replace the certificate |
| Access token | Token endpoint | High. It works as a bearer token for the user's permissions until it expires. | Set by session policy |
| Refresh token | Token endpoint | Critical. It can mint new access tokens without a login. | Until revoked or policy expires it |
| Authorization code | Callback redirect | Medium. Single use and short lived, but it can be stolen in transit. | Minutes |
A bearer token is a token where possession is enough. Salesforce does not check who is presenting it. This is why most of the practices below are about limiting who can see a token, how long it works, and how much it can do.
Store secrets outside the code
Never put the consumer secret, private key, or any token in source code, a Git repository, a container image, or a log line. Keep them in a secret store and load them at run time.
Good options, in rough order of preference:
- A managed secret store such as AWS Secrets Manager, HashiCorp Vault, or your platform's equivalent. These give you access control, audit trails, and rotation.
- Environment variables injected by your deployment platform from a secret store.
- A file with
0600permissions outside the repository, for local development only.
The following Python code reads values from the environment and fails early if one is missing. It also keeps the private key out of the working tree.
import os
import sys
def require_env(name: str) -> str:
value = os.environ.get(name)
if not value:
sys.exit(f"Missing required environment variable: {name}")
return value
consumer_key = require_env("SF_CONSUMER_KEY")
consumer_secret = require_env("SF_CONSUMER_SECRET")
key_path = require_env("SF_PRIVATE_KEY_PATH")
with open(key_path, "rb") as f:
private_key = f.read()
print("Loaded credentials for key ending in", consumer_key[-6:])Note that the last line prints only a short suffix of the consumer key. Never print a full secret or token while debugging.
Add the key and certificate files to .gitignore before you create them:
printf 'server.key\n*.pem\n.env\n' >> .gitignore
git check-ignore -v server.keyIf a secret is committed even once, treat it as leaked. Deleting the file in a later commit does not remove it from history. Rotate the secret first, then clean up the history.
Keep secrets out of the browser
The web server flow runs partly in the user's browser. Only the authorization request and callback pass through it. The token exchange must happen on your server, because it needs the consumer secret.
- Never ship the consumer secret in JavaScript, a mobile app, or a desktop binary. Anything on a user's device can be extracted.
- If your app cannot keep a secret, it is a public client. Use the authorization code flow with PKCE and do not rely on a secret. Check that your connected app's settings allow this, such as turning off the requirement for a secret in the web server flow.
- Always send and verify the
stateparameter. Reject any callback whosestatedoes not match the value you stored for that session. This blocks cross-site request forgery on the callback. - Use PKCE even when you also have a secret. It prevents a stolen authorization code from being redeemed by someone else.
- Register exact callback URLs, over HTTPS. Do not use wildcards or broad paths. A loose callback URL lets an attacker route the authorization code to a place they control.
Limit what a token can do
A leaked token is only as dangerous as its permissions. Reduce the blast radius at three levels.
- Scopes. Request only the scopes the integration needs. For a read-only reporting job,
apiis enough. Avoidfullunless you truly need it. Addrefresh_tokenonly when the app must act while the user is away. - Run-as user and pre-authorized user. For the JWT bearer and client credentials flows, the token carries the permissions of one user. Create a dedicated integration user, not a named employee or an administrator. Give it a profile and permission sets that cover only the objects and fields the integration touches.
- Connected app policies. Use IP restrictions, such as relaxing IP restrictions only when you must and otherwise enforcing them. Set the permitted users to admin-approved users and assign profiles or permission sets, so that only the intended identities can use the app.
Because the scope and the user's permissions both apply, the token gets the smaller of the two. Tightening the user's permissions is often the stronger control. A scope narrows what the app may request, but the user's permissions are the real ceiling.
Handle tokens carefully at run time
Treat access and refresh tokens as passwords.
- Send them only over HTTPS, in the
Authorization: Bearerheader. Never place a token in a URL query string, where it ends up in logs, browser history, and referrer headers. - Keep access tokens in memory where you can. If you must cache them, cache them in an encrypted store, not in plain files or a shared database column.
- Store refresh tokens encrypted at rest, tied to the user they belong to, and readable only by the service that needs them.
- Redact
Authorizationheaders and token fields in application logs, error reports, and HTTP debugging tools. - Do not forward a user's token to a third party. If another service needs access, give it its own connected app or flow.
The next snippet shows a helper that masks a token before it is logged.
def mask(token: str, visible: int = 4) -> str:
if len(token) <= visible:
return "*" * len(token)
return "*" * (len(token) - visible) + token[-visible:]
print(mask("00D5g000000XXXX!AQEAQabcdefghijkl"))Rotate and revoke
Plan for the day a secret leaks. Rotation should be a routine task you have already practiced.
- Consumer secret. Regenerate it in the connected app, update your secret store, and redeploy. Existing tokens keep working, so also revoke them if you suspect misuse.
- Certificate and private key. Generate a new pair, upload the new certificate to the connected app, switch the integration to the new key, and then remove the old certificate. The sample certificate in this tutorial lasts 365 days, so put the expiry date on a calendar.
- Refresh tokens. Revoke them through the revocation endpoint or from the user's connected apps page in Setup. A revoked refresh token also invalidates the access tokens issued from it.
- Access tokens. Keep session timeouts short, so a leaked token expires on its own.
A revocation call looks like this:
curl -X POST https://login.salesforce.com/services/oauth2/revoke \
-d token=<REFRESH_TOKEN>Test rotation in a sandbox. Confirm that the integration fails clearly when a credential is revoked, and that it does not retry forever with a dead token.
Monitor and audit
You cannot respond to misuse you cannot see.
- Review the OAuth Connected Apps list in Setup to see which users authorized which apps and when.
- Use login history for the integration user. An integration that logs in from an unexpected IP address is a warning sign.
- Alert on repeated
invalid_grantorinvalid_clienterrors. They can mean a rotated secret that was not deployed, or someone guessing. - Remove connected apps and certificates that are no longer used.
A checklist for review
- No secret, key, or token appears in source control, images, or logs.
- The consumer secret never reaches a browser or device.
- The web server flow uses
state, PKCE, exact HTTPS callback URLs. - Each integration has its own connected app and its own least-privilege user.
- Scopes are the minimum required.
- Tokens travel only in headers over HTTPS.
- A rotation and revocation procedure exists and has been tested.
- Login and connected app activity is reviewed.
Exercise
Your team committed server.key to a Git repository by mistake, then deleted it in the next commit. The JWT bearer flow integration still works. What should you do, and why is deleting the file not enough?
Show answer
Treat the key as compromised. Generate a new key pair, upload the new certificate to the connected app, switch the integration to the new key, and remove the old certificate so the leaked key can no longer sign valid assertions. Then remove the key from history if needed and add it to .gitignore. Deleting the file is not enough because the key remains in earlier commits and in every clone, so anyone with repository access can still read it.
Exercise
A single-page JavaScript app needs to act on behalf of Salesforce users. A colleague proposes embedding the consumer secret in the bundled script so the app can call the token endpoint directly. What is wrong with this, and what should you do instead?
Show answer
Anything in a browser bundle can be read by any user, so the secret would be public. Use the web server flow with PKCE and a state value, and do not depend on a secret in the browser. If a secret is required, perform the token exchange on a backend server that stores the secret in a secret store. Register an exact HTTPS callback URL and request only the scopes needed.
Exercise
An integration user has the System Administrator profile because it was easy to set up. The connected app requests only the api scope. Is the scope enough to keep the damage small if the token leaks? Explain.
Show answer
No. The scope limits what the app may request, but the token still acts as the user, so the user's permissions are the real ceiling. An administrator profile gives broad access to data and setup. Replace it with a dedicated integration user whose profile and permission sets cover only the required objects and fields.