Created
July 7, 2024 12:16
-
-
Save PaulCreusy/2542cda0ddbddf999715b065f2e3eda5 to your computer and use it in GitHub Desktop.
Python script to authenticate with MFA to Azure and recover the user's email.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from azure.identity import InteractiveBrowserCredential | |
# Define your Azure AD client ID | |
client_id = ... | |
# Define the Microsoft Graph API scope | |
scope = ["User.Read"] | |
# Create the InteractiveBrowserCredential instance | |
credential = InteractiveBrowserCredential(client_id=client_id) | |
# Acquire a token | |
token = credential.get_token(*scope) | |
# Use the access token to call the Microsoft Graph API | |
access_token = token.token | |
headers = { | |
'Authorization': f'Bearer {access_token}', | |
'Content-Type': 'application/json' | |
} | |
# Fetch user profile information | |
graph_url = "https://graph.microsoft.com/v1.0/me" | |
response = requests.get(graph_url, headers=headers) | |
if response.status_code == 200: | |
user_info = response.json() | |
email = user_info.get('mail') or user_info.get('userPrincipalName') | |
print(f"User email: {email}") | |
else: | |
print(f"Failed to retrieve user information: {response.status_code}") | |
print(response.json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment