Skip to content

Instantly share code, notes, and snippets.

@gbaeke
Created Jan 5, 2023
Embed
What would you like to do?
import requests
import json
# url uses a hardcoded identity endpoint
url = "http://127.0.0.1:40342/metadata/identity/oauth2/token?api-version=2019-11-01&resource=https%3A%2F%2Fvault>
headers = {"Metadata": "true"}
# do token request to IMDS, this will fail
r = requests.get(url, headers=headers)
# for security reasons, a cryptographic blob is generated
# get the path to the blob from the Www-Authenticate header
challenge_token_path = r.headers["Www-Authenticate"].split("=")[1].strip()
# read the contents of the file in the challenge_token_path
with open(challenge_token_path, "r") as f:
challenge_token = f.read()
# use basic auth with the contents of the file as password
auth_header = f"Basic {challenge_token}"
headers["Authorization"] = auth_header
r = requests.get(url, headers=headers)
# get the response and extract the access_token
response_text = r.text
response_data = json.loads(response_text)
access_token = response_data["access_token"]
# set key vault variables
api_version="2016-10-01"
key_vault_name="kvname"
secret_name="mysecret"
# set secret url Authorization header
kvurl = f"https://{key_vault_name}.vault.azure.net/secrets/{secret_name}?api-version={api_version}"
headers = {"Authorization": f"Bearer {access_token}"}
# get the secret
r = requests.get(kvurl, headers=headers)
# Print the secret value
print(r.json()["value"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment