Sub topic 5
Authenticating and Sending the Required Metadata Headers
This chapter assumes you can read Python, know what an OAuth 2.0 access token is, and have a connected app or external client app in your Salesforce org. You should also have generated the gRPC stubs from pubsub_api.proto in the previous chapter.
How the Pub/Sub API authenticates a call
The Pub/Sub API does not take a username and password. Every RPC carries three pieces of gRPC metadata. Metadata is a set of key-value pairs sent with a call, much like HTTP headers on a REST request.
| Metadata key | Value | Where it comes from |
|---|---|---|
| `accesstoken` | The OAuth 2.0 access token (session ID) | The OAuth token response |
| `instanceurl` | The org's instance URL, such as `https://mydomain.my.salesforce.com` | The `instance_url` field of the token response |
| `tenantid` | The 18-character org ID | The `id` URL from the token response, or a UserInfo call |
Your code obtains a token with any OAuth flow your org allows, such as the client credentials flow or the JWT bearer flow. The Pub/Sub API only checks the token. It does not care how you got it.
Getting a token
This example uses the client credentials flow. It reads secrets from environment variables so they never appear in source code.
import os
import requests
def get_token():
domain = os.environ["SF_MY_DOMAIN"] # e.g. https://mydomain.my.salesforce.com
response = requests.post(
f"{domain}/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 "id" URL ends with /<org id>/<user id>.
tenant_id = body["id"].split("/")[-2]
return body["access_token"], body["instance_url"], tenant_idThe client credentials flow requires a My Domain URL and an app configured with a run-as user. Other flows return the same three values, so the rest of your code does not change.
Attaching metadata to a call
Pass the metadata as a tuple of pairs on every stub call. This is the helper from the chapter's code example, extended to show a complete call.
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
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 describe_topic(access_token, instance_url, tenant_id, topic_name):
with grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials()) as channel:
stub = pb2_grpc.PubSubStub(channel)
metadata = auth_metadata(access_token, instance_url, tenant_id)
topic = stub.GetTopic(pb2.TopicRequest(topic_name=topic_name), metadata=metadata)
print("can_subscribe:", topic.can_subscribe, "schema_id:", topic.schema_id)
return topic.schema_idgrpc.secure_channel with ssl_channel_credentials() opens a TLS connection using your system's trusted certificate authorities. The API only accepts TLS connections, so an insecure channel will fail.
Common errors
- UNAUTHENTICATED: The token is expired, revoked, or was issued for a different org than
tenantidnames. Fetch a new token and retry. - Missing or misspelled metadata key: gRPC metadata keys must be lowercase.
accessTokenis not the same asaccesstoken. - Wrong
instanceurl: Use theinstance_urlfrom the token response. A hand-typed login URL can mismatch the org the token belongs to. - Permission errors: A valid token still needs access to the topic. The run-as user must be allowed to read the event or object you are subscribing to.
Tokens expire. A long-lived subscriber must refresh its token and send the new value in the metadata of the next call. A stream that is already open keeps working until the server closes it, so plan for the reconnection logic covered in a later chapter.
Exercise
A call to GetTopic fails with UNAUTHENTICATED even though your code sends all three metadata keys. Name two causes you would check first.
Show answer
The access token may have expired or been revoked, so request a new one. The tenantid may belong to a different org than the one that issued the token, so confirm it matches the org ID in the token response's id URL.