Skip to content

Instantly share code, notes, and snippets.

@luisdelatorre012
Created September 20, 2024 01:17
Show Gist options
  • Save luisdelatorre012/9552e0346c25bf7308b1db8cbab10432 to your computer and use it in GitHub Desktop.
Save luisdelatorre012/9552e0346c25bf7308b1db8cbab10432 to your computer and use it in GitHub Desktop.
Console app for displaying current user's info using MSAL
import msal
import httpx
from dynaconf import Dynaconf
# Load configuration
config = Dynaconf(
settings_files=['settings.toml', '.secrets.toml'],
environments=True,
load_dotenv=True,
)
# MSAL configuration
app = msal.PublicClientApplication(
client_id=config.client_id,
authority=config.authority
)
def get_token():
flow = app.initiate_device_flow(scopes=config.scope)
if "user_code" not in flow:
print(f'Failed to create device flow: {flow.get("error")}')
return None
print(flow['message'])
print("Waiting for you to complete the authentication...")
result = app.acquire_token_by_device_flow(flow)
if "access_token" in result:
return result['access_token']
else:
print(f"Authentication failed: {result.get('error')}")
return None
def get_user_info(access_token):
headers = {"Authorization": f"Bearer {access_token}"}
with httpx.Client() as client:
user_response = client.get("https://graph.microsoft.com/v1.0/me", headers=headers)
user_response.raise_for_status()
return user_response.json()
def get_user_groups(access_token):
headers = {"Authorization": f"Bearer {access_token}"}
with httpx.Client() as client:
group_response = client.get("https://graph.microsoft.com/v1.0/me/memberOf", headers=headers)
group_response.raise_for_status()
return [group['displayName'] for group in group_response.json()["value"] if group['@odata.type'] == '#microsoft.graph.group']
def main():
print("User Information App")
print("--------------------")
access_token = get_token()
if not access_token:
print("Failed to acquire access token. Exiting.")
return
try:
user_info = get_user_info(access_token)
groups = get_user_groups(access_token)
print(f"\nWelcome, {user_info['displayName']}!")
print(f"Email: {user_info.get('mail', 'N/A')}")
print("\nYour group memberships:")
for group in groups:
print(f"- {group}")
except httpx.HTTPStatusError as e:
print(f"Error fetching data: {str(e)}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment