Python脚本中的Microsoft Graph API返回“@odata.context”,然后返回一个包含来自请求的select的长字符串

w1e3prcc  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(115)

我正在尝试使用Python通过Microsoft Graph API运行get请求。该请求的目标是查找用户最后一次登录Entra ID的时间。
我正在使用请求'https://graph.microsoft.com/v1.0/users/{user_id}?$select=displayName,lastNonInteractiveSignInDateTime,lastSignInDateTime,userPrincipalName',它返回显示名称和用户主体名称,但它不返回lastNonInteractiveSignInDateTime和lastSignInDateTime。实际回报为:

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

它运行的代码是:

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()

我如何实际获取最后一次登录的值?

rta7y2nd

rta7y2nd1#

lastNonInteractiveSignInDateTimelastSignInDateTimesignInActivity的一部分,仅在$select上返回

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

更新查询

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

您的应用需要AuditLog.Read.All应用权限。

相关问题