This Python code example encodes a JWT based on your client ID, username, and private key. It then issues a request to the /services/oauth2/token endpoint, passing the JWT in the body of the request. The resulting output contains the bearer token, which you use to authenticate subsequent requests to the API.
To run this example, install the requests library and the PyJWT library with added cryptography support. You can install these libraries using pip.
pip install requests "PyJWT[crypto]"
Next, create an environment variable called CLIENTID_DC that contains your client ID (also referred to as your consumer key), and create another environment variable called USER_DC that contains your user ID.
Finally, change the value of the keyFile variable in the main function to refer to your RSA private key.
import jwt
import requests
import json
import sys
import os
import datetime as dt
def encodeJWT(login_url, client_id, username, filename) -> str:
"""
Encode a JWT using the payload and private key type that the Salesforce APIs
expect. Return the encoded JWT.
"""
# Get a Unix timestamp for the current time plus 5 minutes.
current_time = dt.datetime.now(dt.timezone.utc)
expiry = round(current_time.timestamp() + (5 * 60))
with open(filename) as f:
key = f.read()
# The payload to use when creating the JWT.
payload = {
"iss": client_id,
"sub": username,
"aud": login_url,
"exp": expiry
}
# Create the JWT.
encoded = jwt.encode(payload, key, algorithm='RS256')
return encoded
def obtainTokenRequest(assertion, loginUrl) -> dict:
"""
Issue a POST request to obtain the JWT bearer token. Return the API response
object.
"""
req = requests.post(
loginUrl + '/services/oauth2/token',
data = {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': assertion
})
#print('Status:', req.status_code)
return req.json()
def main() -> int:
"""
Create some variables and call the necessary functions. Print the API response
returned by the obtainTokenRequest function.
"""
# Replace the value of the keyFile variable with the full path of your
# private key file.
keyFile = "/path/to/host.key"
# The URL to use to log in to your instance. In some cases, such as when
# you're using a sandbox instance, you must change this value.
loginUrl = "https://login.salesforce.com"
# Retrieve environment variables.
clientId = os.environ.get('CLIENTID_DC')
authorizedUser = os.environ.get('USER_DC')
token = encodeJWT(loginUrl, clientId, authorizedUser, keyFile)
print(obtainTokenRequest(token, loginUrl))
return 0
if __name__ == '__main__':
sys.exit(main())
If the request is successful, the response object includes the access token.
{
'access_token': '00DSB0000023p85!AQEAQM2kTRKkIiXrNHHXkTOsRZPO2vCsj71esL7xxEADntI1wPENsCKOcL3mw2ag3udQYanhaKqI3smq_50XgvkiWy5NCRrx',
'scope': 'cdp_query_api cdp_identityresolution_api cdp_ingest_api cdp_calculated_insight_api cdp_segment_api cdp_profile_api',
'instance_url': 'https://YOUR_SUBDOMAIN.my.salesforce.com',
'id': 'https://login.salesforce.com/id/00BCM0000082q383BC/004TB0000029cmJWM42',
'token_type': 'Bearer'
}