Skip to content

Instantly share code, notes, and snippets.

@jmhublar
Last active March 15, 2023 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmhublar/8e4c3ee398752aa50de3b71f594bb388 to your computer and use it in GitHub Desktop.
Save jmhublar/8e4c3ee398752aa50de3b71f594bb388 to your computer and use it in GitHub Desktop.
A few token utilities
# python appProperties.py --client_id <client_id> --url "https://api-endpoint.okta.com/api/v1/apps/{client_id}" --token "<token>" -o json
import requests
import argparse
import json
import sys
# define the command line arguments
parser = argparse.ArgumentParser(description='Make a call to an API')
parser.add_argument('--client_id', required=True, help='The client ID')
parser.add_argument('--url', required=True, help='The API endpoint URL with a placeholder for the client ID')
parser.add_argument('--token', required=True, help='The authorization token')
parser.add_argument('--app_name', help='The value for the new "appName" property')
parser.add_argument('-o', '--output', choices=['json'], help='Output format')
# parse the command line arguments
args = parser.parse_args()
# set the URL with the client ID placeholder replaced
url = args.url.format(client_id=args.client_id)
# make the API call with the token in the headers
headers = {'Authorization': 'SSWS ' + args.token}
response = requests.get(url, headers=headers)
if args.app_name is None:
if args.output == 'json':
# output the content as JSON to stdout
data = json.loads(response.content)
json.dump(data, sys.stdout)
else:
# print the response status code and content as a string to stdout
print('Status code:', response.status_code)
print('Content:', response.content)
else:
# parse the response content as JSON
data = json.loads(response.content)
# add the new "appName" property to the root level of the JSON object
data['appName'] = args.app_name
# make a PUT request to the same URL with the modified data
response = requests.put(url, headers=headers, json=data)
if args.output == 'json':
# output the modified content as JSON to stdout
json.dump(data, sys.stdout)
else:
# print the response status code and content as a string to stdout
print('Status code:', response.status_code)
print('Content:', response.content)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import jwt
import sys
import fileinput
def decode_jwt(token, secret_key=None, algorithms=None):
try:
if secret_key and algorithms:
decoded_token = jwt.decode(token, secret_key, algorithms=algorithms)
else:
decoded_token = jwt.decode(token, options={"verify_signature": False})
return decoded_token
except jwt.InvalidTokenError as e:
print(f"Error decoding JWT: {e}")
sys.exit(1)
if __name__ == "__main__":
token = None
secret_key = None
algorithms = None
for line in fileinput.input():
if not token:
token = line.strip()
elif not secret_key:
secret_key = line.strip()
elif not algorithms:
algorithms = line.strip().split(",")
if not token:
print("Usage: echo <jwt_token> [secret_key] [algorithms] | python decode_jwt.py")
sys.exit(1)
decoded_token = decode_jwt(token, secret_key, algorithms)
print(f"Decoded JWT: {decoded_token}")
import os
import base64
import requests
def get_auth_token(client_id, client_secret):
credentials = f"{client_id}:{client_secret}"
auth_token = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
return auth_token
def get_token(auth_token, issuer_url):
url = f"{issuer_url}/v1/token"
headers = {
"Authorization": f"Basic {auth_token}",
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials"
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
return response.json().get("access_token")
else:
raise Exception(f"Error retrieving token: {response.status_code} - {response.text}")
if __name__ == "__main__":
client_id = os.environ.get("CLIENT_ID")
client_secret = os.environ.get("CLIENT_SECRET")
issuer_url = os.environ.get("ISSUER_URL")
if not client_id or not client_secret or not issuer_url:
raise ValueError("CLIENT_ID, CLIENT_SECRET, and ISSUER_URL environment variables must be set")
auth_token = get_auth_token(client_id, client_secret)
access_token = get_token(auth_token, issuer_url)
print(f"{access_token}")
Token Utilities
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment