Python Code Example for Encoding a JWT

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.

1pip 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.

1import jwt
2import requests
3import json
4import sys
5import os
6import datetime as dt
7
8def encodeJWT(login_url, client_id, username, filename) -> str:
9	"""
10	Encode a JWT using the payload and private key type that the Salesforce APIs
11	expect. Return the encoded JWT.
12	"""
13
14	# Get a Unix timestamp for the current time plus 5 minutes.
15	current_time = dt.datetime.now(dt.timezone.utc)
16	expiry = round(current_time.timestamp() + (5 * 60))
17
18	with open(filename) as f:
19		key = f.read()
20
21		# The payload to use when creating the JWT.
22		payload = {
23			"iss": client_id,
24			"sub": username,
25			"aud": login_url,
26			"exp": expiry
27		}
28
29	# Create the JWT.
30	encoded = jwt.encode(payload, key, algorithm='RS256')
31
32	return encoded
33
34def obtainTokenRequest(assertion, loginUrl) -> dict:
35	"""
36	Issue a POST request to obtain the JWT bearer token. Return the API response
37	object.
38	"""
39	req = requests.post(
40      loginUrl + '/services/oauth2/token',
41      data = {
42        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
43        'assertion': assertion
44      })
45
46	#print('Status:', req.status_code)
47	return req.json()
48
49def main() -> int:
50	"""
51	Create some variables and call the necessary functions. Print the API response
52	returned by the obtainTokenRequest function.
53	"""
54
55	# Replace the value of the keyFile variable with the full path of your
56	# private key file.
57	keyFile = "/path/to/host.key"
58
59	# The URL to use to log in to your instance. In some cases, such as when
60	# you're using a sandbox instance, you must change this value.
61	loginUrl = "https://login.salesforce.com"
62
63	# Retrieve environment variables.
64	clientId = os.environ.get('CLIENTID_DC')
65	authorizedUser = os.environ.get('USER_DC')
66
67	token = encodeJWT(loginUrl, clientId, authorizedUser, keyFile)
68	print(obtainTokenRequest(token, loginUrl))
69	return 0
70
71if __name__ == '__main__':
72    sys.exit(main())

If the request is successful, the response object includes the access token.

1{
2  'access_token': '00DSB0000023p85!AQEAQM2kTRKkIiXrNHHXkTOsRZPO2vCsj71esL7xxEADntI1wPENsCKOcL3mw2ag3udQYanhaKqI3smq_50XgvkiWy5NCRrx',
3  'scope': 'cdp_query_api cdp_identityresolution_api cdp_ingest_api cdp_calculated_insight_api cdp_segment_api cdp_profile_api',
4  'instance_url': 'https://YOUR_SUBDOMAIN.my.salesforce.com',
5  'id': 'https://login.salesforce.com/id/00BCM0000082q383BC/004TB0000029cmJWM42',
6  'token_type': 'Bearer'
7}