Search code examples
python-3.xmicrosoft-graph-api

Microsoft Graph API in python script returns '@odata.context' and then a long string containing the select from the request


I'm trying to run a get request through the Microsoft Graph API using Python. The goal of the request is to find the last time a user had any type of login to Entra ID.

I'm using the request 'https://graph.microsoft.com/v1.0/users/{user_id}?$select=displayName,lastNonInteractiveSignInDateTime,lastSignInDateTime,userPrincipalName' and it returns the display name and user principle name fine, but it doesn't return the lastNonInteractiveSignInDateTime and lastSignInDateTime. The actual return is:

'{'@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users(displayName,lastNonInteractiveSignInDateTime,lastSignInDateTime,userPrincipalName)/$entity', 'displayName': '****', 'userPrincipalName': '****'}'

The code it is running is:

import requests

def retrieveAzureAD():
    # Azure app registration settings
    CLIENT_ID = CLIENT_ID 
    CLIENT_SECRET = CLIENT_SECRET 
    TENANT_ID = TENANT_ID 
    RESOURCE = "https://graph.microsoft.com"
    TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/token"

    # Token configuration
    token_data = {
        'grant_type': 'client_credentials',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'resource': RESOURCE
    }

    # Fetch token
    token_r = requests.post(TOKEN_URL, data=token_data)
    token = token_r.json().get('access_token')

    # Headers
    headers = {
        'Authorization': f'Bearer {token}'
    }

    user_id = '****'

    action_r = requests.get(
        f'https://graph.microsoft.com/v1.0/users/{user_id}?$select=displayName,lastNonInteractiveSignInDateTime,lastSignInDateTime,userPrincipalName',
        headers=headers
    )

    print(action_r)
    last_action = "N/A"
    actions = action_r.json()
    print(actions)

retrieveAzureAD()

How do I actually get the last sign in values?


Solution

  • The lastNonInteractiveSignInDateTime and lastSignInDateTime are part of signInActivity which is returned only on $select

    GET /v1.0/users/{user_id}?$select=displayName,signInActivity,userPrincipalName
    

    Update the query

    action_r = requests.get(
            f'https://graph.microsoft.com/v1.0/users/{user_id}?$select=displayName,signInActivity,userPrincipalName',
            headers=headers
        )
    

    Your app needs AuditLog.Read.All application permission.