Sub topic 5
Authenticating and sending the required metadata headers
Every call to the Pub/Sub API must prove who you are and which org you are asking about. This chapter shows how to obtain an OAuth access token, derive the other two values the API needs, and attach all three to your gRPC calls.
It assumes you can read Python, know what an OAuth 2.0 access token is, and have an external client app or connected app in a Salesforce org. It also assumes you have already generated the pubsub_api_pb2 and pubsub_api_pb2_grpc modules from pubsub_api.proto.
What the API expects
The Pub/Sub API does not use an HTTP Authorization: Bearer header. It reads three custom gRPC metadata entries on each call.
| Metadata key | Value | Where it comes from |
|---|---|---|
| `accesstoken` | The OAuth access token (session ID) | The token endpoint response |
| `instanceurl` | The base URL of your org, such as `https://mydomain.my.salesforce.com` | The `instance_url` field in the token response |
| `tenantid` | The 18-character org ID, starting with `00D` | The `id` field in the token response, or the userinfo endpoint |
Metadata is a set of key-value pairs sent with the call, much like HTTP headers. In Python's grpc library it is a tuple of (key, value) tuples. Keys must be lowercase. That is why they are written accesstoken and not accessToken.
All three are required. If one is missing or wrong, the server rejects the call before any of your request fields are read.
The authentication flow
Authentication has two stages. First you talk to Salesforce over normal HTTPS to get a token. Then you use that token against the gRPC endpoint.
The token endpoint lives on your org's My Domain, not on the Pub/Sub host. The gRPC endpoint is the same for every org: api.pubsub.salesforce.com:7443. The instanceurl and tenantid metadata tell it which org to serve.
Choosing an OAuth flow
Any flow that returns a valid access token for a user with API access works. These are the common choices for a server-side subscriber.
- Client credentials flow. You send a client ID and client secret. The app is configured to run as a specific integration user. This is the simplest option for unattended services, and the examples below use it.
- JWT bearer flow. You sign an assertion with a private key and exchange it for a token. No secret crosses the wire, and it suits automated deployments where you want certificate-based trust.
- Authorization code flow with refresh tokens. Use this when a person must log in and grant access.
The integration user needs the API Enabled permission, and your app's OAuth scopes must include api. Access to the events themselves is controlled by object and field permissions, or by event-specific permissions. A valid token does not guarantee you can read every topic.
Getting a token with client credentials
The following function posts to the token endpoint and returns the three values. It reads secrets from environment variables, so nothing sensitive is in the source file.
import os
import requests
def get_credentials():
login_url = os.environ["SF_LOGIN_URL"] # e.g. https://mydomain.my.salesforce.com
response = requests.post(
f"{login_url}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": os.environ["SF_CLIENT_ID"],
"client_secret": os.environ["SF_CLIENT_SECRET"],
},
timeout=30,
)
response.raise_for_status()
body = response.json()
# The identity URL looks like https://login.salesforce.com/id/<orgId>/<userId>
org_id = body["id"].rstrip("/").split("/")[-2]
return body["access_token"], body["instance_url"], org_id
if __name__ == "__main__":
token, instance_url, org_id = get_credentials()
print("instance_url:", instance_url)
print("org_id:", org_id)The id field in the response is an identity URL. Its last two path segments are the org ID and the user ID, so the second-to-last segment is the value you need for tenantid. If you prefer not to parse a URL, you can call /services/oauth2/userinfo with the token and read organization_id from the JSON.
Never print the access token or secret in logs. Printing the instance URL and org ID is fine for debugging.
Attaching metadata to calls
The metadata goes on each RPC call, not on the channel. Build it once and pass it as the metadata argument. The helper below reuses the connection pattern from the topic-discovery example.
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
from get_credentials_module import get_credentials # the function above, saved as get_credentials_module.py
ENDPOINT = "api.pubsub.salesforce.com:7443"
def auth_metadata(access_token, instance_url, tenant_id):
return (
("accesstoken", access_token),
("instanceurl", instance_url),
("tenantid", tenant_id),
)
def main():
token, instance_url, org_id = get_credentials()
metadata = auth_metadata(token, instance_url, org_id)
with grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials()) as channel:
stub = pb2_grpc.PubSubStub(channel)
topic = stub.GetTopic(
pb2.TopicRequest(topic_name="/event/Order_Event__e"),
metadata=metadata,
)
print("can_subscribe:", topic.can_subscribe)
print("schema_id:", topic.schema_id)
if __name__ == "__main__":
main()Save the first listing as get_credentials_module.py next to this file. Replace /event/Order_Event__e with a topic that exists in your org.
Two details matter here.
grpc.secure_channelwithssl_channel_credentials()uses TLS and the system's trusted certificate authorities. The API only accepts TLS connections, so there is no plaintext option to fall back to.- For a streaming call such as
Subscribe, the metadata is sent once when the stream opens, at the start of the call. The same tuple works forGetTopic,GetSchema, andSubscribe.
Token lifetime and long-running subscribers
An access token is a Salesforce session, and sessions expire. The length depends on your org's session settings and the app's policies, so do not hard-code an assumption such as "one hour".
A subscriber that runs for days therefore needs a plan:
- Treat an authentication failure as a normal event, not a crash.
- Obtain a fresh token using the same flow. With client credentials or JWT bearer, this is another POST. With the authorization code flow, use the refresh token.
- Rebuild the metadata tuple with the new token and open a new call.
- Resume the subscription from your last stored replay ID so you do not lose events. Replay IDs are covered in a later chapter.
Because the token is sent when a call starts, a stream that is already open does not pick up a new token you create afterward. Plan on reconnecting. Keep the credential-fetching code in a function you can call again, as get_credentials is above, rather than reading the token once at startup.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `UNAUTHENTICATED` status on the first call | Expired or invalid token, or a token from a different org than `instanceurl` | Fetch a new token and confirm all three values come from the same response |
| `INVALID_ARGUMENT` or a missing-header error | A metadata key is misspelled, or a value is empty | Print the key names (not the values) and compare with the table above |
| `PERMISSION_DENIED` on `GetTopic` or `Subscribe` | The user lacks access to that event or object | Grant the permission set to the integration user, then retry |
| Token request returns `invalid_grant` or `invalid_client` | Wrong login URL, wrong secret, or the app is not enabled for the flow | Use the My Domain URL, and check the app's OAuth settings |
| `tenantid` rejected | You passed the 15-character ID or a user ID | Use the 18-character org ID starting with `00D` |
When you are unsure which layer is failing, test the token alone. Call /services/oauth2/userinfo with Authorization: Bearer <token>. If that fails, the problem is with the OAuth setup and not with gRPC.
Exercises
Exercise
A teammate's subscriber works for several hours and then every call fails with UNAUTHENTICATED. The code fetches the token once at startup. What is the cause, and what should the subscriber do when it sees this error?
Show answer
The access token is a Salesforce session that expired. The subscriber should catch the authentication failure, request a new token with the same OAuth flow, rebuild the metadata tuple with the new accesstoken (the instanceurl and tenantid normally stay the same), open a new call, and resume from the last stored replay ID so no events are missed.
Exercise
The token response contains the id value "https://login.salesforce.com/id/00D5g000001AbCdEAK/0055g00000XyZaBAAZ". Which part is the tenantid, and which line of Python extracts it?
Show answer
The tenantid is 00D5g000001AbCdEAK, the org ID. It is the second-to-last path segment, extracted with body["id"].rstrip("/").split("/")[-2]. The last segment is the user ID.