43 lines
1.4 KiB
Python
43 lines
1.4 KiB
Python
import requests
|
|
import json
|
|
import os
|
|
|
|
TENANT_ID = os.environ.get("AZURE_TENANT_ID")
|
|
CLIENT_ID = os.environ.get("AZURE_CLIENT_ID")
|
|
CLIENT_SECRET = os.environ.get("AZURE_CLIENT_SECRET")
|
|
|
|
SCOPE = "https://graph.microsoft.com/.default"
|
|
TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
|
|
|
|
def get_access_token():
|
|
headers = {
|
|
"Content-Type": "application/x-www-form-urlencoded"
|
|
}
|
|
data = {
|
|
"grant_type": "client_credentials",
|
|
"client_id": CLIENT_ID,
|
|
"client_secret": CLIENT_SECRET,
|
|
"scope": SCOPE
|
|
}
|
|
|
|
try:
|
|
response = requests.post(TOKEN_URL, headers=headers, data=data)
|
|
response.raise_for_status()
|
|
token_data = response.json()
|
|
access_token = token_data.get("access_token")
|
|
if access_token:
|
|
print(access_token)
|
|
return access_token
|
|
else:
|
|
print(f"Error: 'access_token' not found in response. Response: {token_data}", file=os.sys.stderr)
|
|
return None
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"Error making request to Azure AD: {e}", file=os.sys.stderr)
|
|
if hasattr(response, 'status_code'):
|
|
print(f"Response status code: {response.status_code}", file=os.sys.stderr)
|
|
print(f"Response body: {response.text}", file=os.sys.stderr)
|
|
return None
|
|
|
|
if __name__ == "__main__":
|
|
get_access_token()
|