I've been able to access azure key vault using oauth rest api through my external web app, but for some reason I am unable to retrieve the secrets from the keys. After long hours of researching I've found out that its possible to do this with powershell and c# but have still yet to find any solution with python. Anyone know if its possible with python, or is there a way of emulating what powershell is doing through? Here's the code to retrieve the secret:
def getSecret(vault_name, secret_name, secret_version = ''):
#Get acess token to azure account
data = { "grant_type" : "client_credentials",
"client_id" : 'appidxx',
"client_secret" : 'appsecretxx',
"resource" : "https://vault.azure.net"
}
headers = { "Content-Type" : "application/x-www-form-urlencoded" }
r = requests.post("https://login.windows.net/{}/oauth2/token".format('my tenant id'), data=data, headers=headers)
access_token = r.json()['access_token']
#Get secret from KeyVault
headers = {"Authorization":"Bearer {}".format(access_token) }
r = requests.get('https://{}.vault.azure.net/secrets/{}/{}?api-version=2015-06-01'.format(vault_name, secret_name, secret_version), headers=headers)
result = r.json()
if 'value' in result.keys():
return result["value"]
else:
return 'Secret Not Found'
def searchSecret(secret_name, secret_version = ''):
subscription_id = 'subscription id'
credentials = ServicePrincipalCredentials(
client_id= 'appidxx',
secret= 'appsecretxx',
tenant= 'tenantidxx'
)
kvm_client = KeyVaultManagementClient(credentials, subscription_id )
for vault in kvm_client.vaults.list():
#return when secret found in vault
secret = getSecret(vault.name, secret_name, secret_version = '')
if (secret != 'Secret Not Found'):
return secret
return 'Secret Not Found'
Also I have registered my app in azure portal and granted permissions to my keys and secrets, however i noticed that when granting access to my app through access policy, the "Authorized application" option is locked and i cannot add my app, which may be the root cause of my issue?? screenshot
https://login.microsoftonline.com
instead ofhttps://login.windows.net
. Though it won't fix the problem. At a glance I could not see anything really wrong with the code. The authorized application thing in Key Vault is not needed. You granted permissions to the service principal. – juunas