Skip to content

Instantly share code, notes, and snippets.

@dazfuller
Last active August 17, 2018 15:29
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 dazfuller/05eca30e0020a3fc5f2c8f7adb0f2ae3 to your computer and use it in GitHub Desktop.
Save dazfuller/05eca30e0020a3fc5f2c8f7adb0f2ae3 to your computer and use it in GitHub Desktop.
Calling an Azure Active Directory (AAD) secured Azure Function from Python
import json
import requests
with open('settings.json', 'r') as fp:
settings = json.load(fp)
CLIENT_ID = settings['clientId']
CLIENT_SECRET = settings['clientSecret']
TENANT_ID = settings['tenantId']
APP_ID_URI = settings['appIdUri']
auth_body = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'resource': APP_ID_URI
}
auth_uri = 'https://login.microsoftonline.com/{}/oauth2/token'.format(TENANT_ID)
auth_resp = requests.post(auth_uri, data=auth_body, headers={'Content-Type': 'application/x-www-form-urlencoded'})
if not auth_resp.ok:
print('Failed to authenticate')
print(auth_resp.text)
exit(-1)
bearer_token = auth_resp.json()['access_token']
res = requests.get(
'https://<functions app>.azurewebsites.net/<function>?code=<function key>',
headers = {'Authorization': 'Bearer {}'.format(bearer_token)})
print(json.dumps(res.json(), indent=2))
{
"tenantId": "<Azure tenant ID>,
"clientId": "<Application ID>",
"clientSecret": "<Application Client Secret>",
"appIdUri": "<Application ID URI>"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment