Skip to content

Instantly share code, notes, and snippets.

@MatsAnd
Created October 18, 2022 06:38
Show Gist options
  • Save MatsAnd/2beaa29e8713f21d332fa0139b01283e to your computer and use it in GitHub Desktop.
Save MatsAnd/2beaa29e8713f21d332fa0139b01283e to your computer and use it in GitHub Desktop.
Pulls jwks keys from OAuth2 endpoints and stores on disk. Use python v2.7
import os, urllib2, json, re, textwrap
keys_path = "keys/"
keys_file_prefix = "jwks-"
keys_file_ext = ".crt"
remove_old_keys = True
idp_jwks = {
"AAD_V1": "https://login.windows.net/common/discovery/keys",
"AAD_V2": "https://login.microsoftonline.com/common/discovery/v2.0/keys",
}
kids = []
# Loop IDPs
for idp in idp_jwks:
url = idp_jwks[idp]
print("Loading jwks keys for", idp, "from", url)
try:
# Load json from URL and parse response
response = urllib2.urlopen(url)
data = json.loads(response.read())
except Exception as e:
print("Unable to poll jwks from", url, "with error:", str(e))
exit(1)
# Loop keys from keys endpoint
for key in (x for x in data["keys"] if x["kid"]):
kid = key["kid"]
# Create valid certificate
x5c = ["-----BEGIN CERTIFICATE-----\n" + textwrap.fill(cert, 64) + "\n-----END CERTIFICATE-----" for cert in key["x5c"]]
# Create certificate files
with open(keys_path + "/" + keys_file_prefix + kid + keys_file_ext, "w") as f:
f.write("\n".join(x5c))
print("Wrote cert file for", kid)
# Append to keys list
kids.append(kid)
# Cleanup old keys
if remove_old_keys:
# Loop existing crts
for file in os.listdir(keys_path):
kid_search = re.search((keys_file_prefix + '(.*)' + keys_file_ext), file)
# Not matching name format - continue
if not kid_search: continue
# Get parsed kid
file_kid = kid_search.group(1)
# If kid is part of created certs this run, continue loop without removal
hasKid = False
for kid in kids:
if kid == file_kid:
hasKid = True
if not hasKid:
print("Removing expired kid", file_kid)
os.remove(keys_path + "/" + file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment