Search code examples
azure-active-directorymicrosoft-graph-apimicrosoft-graph-sdksmicrosoft-entra-id

Getting count of all SignIns for Enterprise Apps in AAD


I'm working on the automation of AAD App Registrations cleanup, where I want to delete all unused applications. By 'unused' I mean apps with no sign-ins during the last X months. This information is already available to me in the Azure portal for each Enterprise Application, here is an example for Service Principal sign-ins: enter image description here

I need to extract the same data but using a script. Where is the Azure Portal getting the data from?

I thought I could get this data from Graph API, so I tried querying the following endpoint. Notice I'm using "Beta" because "v1.0" doesn't seem to support non-interactive sign-ins:

GET https://graph.microsoft.com/beta/auditLogs/signins

This query indeed returns some sign-in logs so I tried additional filtering by AppId:

GET https://graph.microsoft.com/beta/auditLogs/signins?$filter=appId+eq+'<my-app-id>'

When I provide AppId extracted from the unfiltered result it also works i.e. narrows down the result to a specific App. So in general, the filtering query seems to work as well.

However, when I provide AppId extracted from the Azure Portal for the same application the screenshot above was taken for, I get empty results. It seems that Graph API doesn't return complete results.

To summarize: how can I extract the same signin data I see in Portal via Graph API or Powershell script?


Solution

  • I have one service principal named app1 with below login details from Portal:

    enter image description here

    To get the same results via PowerShell, I ran below script and got response successfully:

    Connect-MgGraph -Scope "AuditLog.Read.All" -NoWelcome
    $signIns = Get-MgBetaAuditLogSignIn -Filter "(signInEventTypes/any(t: t eq 'servicePrincipal')) and (appId eq 'appClientId') and (createdDateTime ge 2023-12-14 and createdDateTime lt 2023-12-21)"
    $signIns | Select-Object "createdDateTime","Id","ServicePrincipalId","ServicePrincipalName","IPAddress","ResourceDisplayName","ResourceId" | ft
    $signIns.Count
    

    Response:

    enter image description here

    To get these SignIn details via Graph API, you can make use of below query by granting AuditLog.Read.All permission like this:

    GET https://graph.microsoft.com/beta/auditLogs/signins?&$filter=(signInEventTypes/any(t: t eq 'servicePrincipal')) and (appId eq 'appClientId') and (createdDateTime ge 2023-12-14 and createdDateTime lt 2023-12-21)
    

    Response:

    enter image description here

    Reference: List signIns - Microsoft Graph beta