Advertisement
kot_mapku3

Get access_token as JWT from IdP

Jan 25th, 2024
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. import json
  2. import time
  3. import requests
  4. import jwt
  5. import os
  6. from dotenv import load_dotenv
  7.  
  8. load_dotenv()
  9.  
  10. ZITADEL_DOMAIN = os.getenv("ZITADEL_DOMAIN")
  11. CLIENT_PRIVATE_KEY_FILE_PATH = os.getenv("CLIENT_PRIVATE_KEY_FILE_PATH")
  12. ZITADEL_TOKEN_URL = os.getenv("ZITADEL_TOKEN_URL")
  13. PROJECT_ID = os.getenv("PROJECT_ID")
  14.  
  15. # Load the downloaded JSON file
  16. with open(CLIENT_PRIVATE_KEY_FILE_PATH, "r") as f:
  17.     json_data = json.load(f)
  18.  
  19. private_key = json_data["key"]
  20. kid = json_data["keyId"]
  21. user_id = json_data["userId"]
  22.  
  23. # Create JWT header and payload
  24. header = {
  25.     "alg": "RS256",
  26.     "kid": kid
  27. }
  28.  
  29. payload = {
  30.     "iss": user_id,
  31.     "sub": user_id,
  32.     "aud": ZITADEL_DOMAIN,
  33.     "iat": int(time.time()),
  34.     "exp": int(time.time()) + 3600
  35. }
  36.  
  37. # Sign the JWT
  38. jwt_token = jwt.encode(payload, private_key, algorithm='RS256', headers=header)
  39.  
  40. # Request an OAuth token from ZITADEL
  41. data = {
  42.     "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
  43.     "scope": f"openid profile email urn:zitadel:iam:org:project:id:{PROJECT_ID}:aud read:messages",
  44.     "assertion": jwt_token
  45. }
  46.  
  47. response = requests.post(ZITADEL_TOKEN_URL, data=data)
  48.  
  49. if response.status_code == 200:
  50.     access_token = response.json()["access_token"]
  51.     print(f"Response: {response.json()}")
  52.     print(f"Access token: {access_token}")
  53. else:
  54.     print(f"Error: {response.status_code} - {response.text}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement