Skip to content

Instantly share code, notes, and snippets.

@keathmilligan
Created December 12, 2020 16:38
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 keathmilligan/7d73a88b71090a86a038f3a03ecf9cb9 to your computer and use it in GitHub Desktop.
Save keathmilligan/7d73a88b71090a86a038f3a03ecf9cb9 to your computer and use it in GitHub Desktop.
MSAL Application/Client Secret Example
# Example of a priviledged application client using a client secret
import os
import atexit
import json
import msal
import requests
TENANT_ID = '<your-tenant-id>'
CLIENT_ID = '<your-client-id>'
CLIENT_SECRET = '<your-client-secret>'
AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'
SCOPE = ['https://graph.microsoft.com/.default']
cache = msal.SerializableTokenCache()
if os.path.exists('token_cache.bin'):
print('reading token cache')
cache.deserialize(open('token_cache.bin', 'r').read())
atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)
print('creating app')
app = msal.ConfidentialClientApplication(
CLIENT_ID,
authority=AUTHORITY,
client_credential=CLIENT_SECRET,
token_cache=cache
)
result = app.acquire_token_silent(SCOPE, account=None)
if not result:
print('getting a token')
result = app.acquire_token_for_client(scopes=SCOPE)
if 'access_token' in result:
print('got token')
headers = {'Authorization': 'Bearer ' + result['access_token']}
print('get users')
result = requests.get(f'{ENDPOINT}/users', headers=headers)
print(result, result.json())
else:
print('could not get token')
print(result.get('error'))
print(result.get('error_description'))
print(result.get('correlation_id'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment