Skip to content

Instantly share code, notes, and snippets.

@gramidt
Last active November 19, 2018 15:56
Show Gist options
  • Save gramidt/2b8c68bba77187f256b518204f588c51 to your computer and use it in GitHub Desktop.
Save gramidt/2b8c68bba77187f256b518204f588c51 to your computer and use it in GitHub Desktop.
Download and combine the Json Web Keys (JWKs) into a single JWK for all of the specified Azure Active Directory B2C (AAD B2C) policies on a tenant.
"""Download and combine Azure Active Directory B2C JWKs.
Download and combine the Json Web Keys (JWKs) into a single JWK for all of the specified Azure Active Directory B2C (AAD B2C) policies on a tenant.
Example:
$python build-aad-b2c-combined-policy-jwk.py --tenant_url https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com --policies b2c_1_sign_in,b2c_1a_another_policy
"""
import sys
import argparse
import requests
import json
parser = argparse.ArgumentParser(description='Download and combine JWKs for Microsoft Azure Active Directory B2C policies')
parser.add_argument('--tenant_url', help='https://login.microsoftonline.com/<tenant_name_or_id>', type=str, nargs=1)
parser.add_argument('--policies', help='comma delimited list of policies', type=str)
parser.add_argument('--out_jwk',
nargs='?',
help='JWK to export',
type=argparse.FileType('w'),
default=sys.stdout)
args = parser.parse_args()
tenant_url = args.tenant_url[0]
policies = args.policies.split(',')
combined_jwk = { 'keys': [] }
keys_added = set()
for policy in policies:
policy_jwk_url = tenant_url + '/discovery/v2.0/keys?p=' + policy
jwk_response = requests.get(policy_jwk_url)
if jwk_response.status_code == 200:
jwk = json.loads(jwk_response.content)
for key in jwk['keys']:
kid = key['kid']
if kid not in keys_added:
keys_added.add(kid)
combined_jwk['keys'].append(key)
with args.out_jwk as out_jwk:
out_jwk.write(json.dumps(combined_jwk, indent=4, sort_keys=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment