Follow these steps to create JWT tokens using Python library.
For ease of readability, the following script is divided into multiple steps. If needed, you can copy/paste the script into a single file and run it.
- Install necessary packages:
pip install pyjwt pip install cryptography
- Set variables:
kid = 'KeyForJwtForPAT02' # Ensure that .pem is not appended to the kid. pat = '<PAT>' Organization Name = '<Organization Identifier>' sub = '<user name> ' # User name of the database user private_key_path = "/Users/<user name>/<Drive path?/KeyForJwtForPAT02.pem"
You can get the Organization Name from the Home page of the VantageCloud Lake Console. It appears similar to:Similarly, you can get the Account ID from the URL. For example, in the URL: https://<org-name>/innovationlabs.teradata.com/environments/9eydr2-yt/dashboard, the part 9eydr2-yrt is the Account ID.
- Read private key file:
import argparse import datetime import jwt import requests from cryptography.hazmat.primitives.serialization import load_pem_private_key org_key = 'XXX' sub = 'XX' kid = 'XXX' # Always replace with the actual key. pemkey = 'XXXX' urlsystem = 'https://XX.innovationlabs.teradata.com/api/accounts/974c1971-7326-42f7-8263-9033839d15b9/' pat = 'XXXX'
- Load the private key:
with open(pemkey, 'rb') as key_file: private_key = load_pem_private_key(key_file.read(), password=None)
- Get JWT for access:
headers = { "alg": "RS256", "typ": "JWT", "kid": kid } payload = { "aud": ["td:service:authentication"], "exp": int(datetime.datetime.now().timestamp()) + 3600, "iat": int(datetime.datetime.now().timestamp()), "iss": "wiki", "org_key": org_key, "multi-use": True, "pat": pat_switch, "sub": sub }
- Sign the JWT token:
bearer_token = jwt.encode(payload, private_key, algorithm="RS256", headers=headers) headers = {'Accept': "application/json","Authorization": f"Bearer {bearer_token}"} url = urlsystem+ "baas/jobs" response = requests.get(url, headers=headers) print(response.json())
- Make a note of the JWT token to use while calling APIs.