In this article, we’ll show you how to get the last login date and sign-in activity of your Azure Active Directory users, export and analyze Azure sign-in and audit logs in your Microsoft tenant using PowerShell (with the AzureADPreview module or Microsoft Graph API).
The easiest way to view user activity logs is to use the Azure portal. Open https://portal.azure.com -> Azure AD -> Users -> select a user -> Sign-in logs. User logon history is shown in the following table.
You can get the user’s last logon date, the operating system on a user device, location, user-agent, etc. You can configure filters by different parameters, add/remove columns, or export data to a CSV file.
However, if you want to get the sign-in activity for multiple or all users, you will have to use PowerShell. There are two ways of getting access to user sign-in logs in Azure.
How to Get User Login History in Azure AD Using Microsoft Graph API?
Let’s try to get user sign-in logs using Microsoft Graph API. Connect to your Azure tenant using Microsoft Graph API.
$ApplicationID = "4434ad23-b212-3212-3aad-54321de3bbc"
$TenatDomainName = "26216542-aaaa-bbbb-2212-65566aa6c32"
$AccessSecret="12-32Bh654321d3-seLa23l33p.hhj33MM21aaf"
$Body = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $ApplicationID
Client_Secret = $AccessSecret
}
$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenatDomainName/oauth2/v2.0/token" -Method POST -Body $Body
$token = $ConnectGraph.access_token
After receiving a token, you can connect to the REST API to get information about user sign-in activity:
$GraphSignInLogs = "https://graph.microsoft.com/v1.0/auditLogs/signIns"
(Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $GraphSignInLogs -Method Get).value
Make sure that you can get data about user authentication events in Azure:
@odata.nextLink
.You can use the Azure Graph Explorer (https://developer.microsoft.com/en-us/graph/graph-explorer) to select the names of columns (object attributes) you want to see in the user login history report. For example, I want to see the information about a user, operating system, Azure/Microsoft 365 app used for connection and location in the report (these are the following columns: userDisplayName
, userPrincipalName
, appDisplayName
, location
, ipAddress
, clientAppUsed
, deviceDetail
, createdDateTime
).
In this example, I want to get an Azure user activity report for the last 90 days:
$SetDate = (Get-Date).AddDays(-90)
$SetDate = Get-Date($SetDate) -format yyyy-MM-dd
$GraphSignInLogs = "https://graph.microsoft.com/v1.0/auditLogs/signIns"
$result = (Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $GraphSignInLogs -Method Get).value | Select-Object userDisplayName, userPrincipalName, appDisplayName, ipAddress, clientAppUsed, deviceDetail, location,createdDateTime | Where-Object {$_.createdDateTime -gt $SetDate }
$alluserhistory = @()
foreach ($resitem in $result){
$userhistory = New-Object PSObject -Property @{
User=$resitem.userDisplayName
UPN=$resitem.userPrincipalName
AzureAppUsed =$resitem.appDisplayName
UserApp =$resitem.clientAppUsed
IP=$resitem.ipAddress
Date=$resitem.createdDateTime
OS=($resitem.deviceDetail).operatingSystem
browser=($resitem.deviceDetail).browser
City=($resitem.location).city
Country=($resitem.location).countryOrRegion
}
$alluserhistory += $userhistory
}
To export the result to a CSV file, run the command below:
$alluserhistory| Export-Csv "C:\PS\azure_signin_logs.csv" –NoTypeInformation
The CSV file contains information about all user activities: what devices and locations they logged on from, what Microsoft apps they used. You can add any other fields if necessary.
To get the last logon date for every AAD user in the list, run this command:
$alluserhistory| Group-Object UPN |%{ $_.Group | Select UPN,Date -First 1}
You can find all inactive Azure users for the specified period of time. To do it, get a full list of user UserPrincipalNames (UPNs) in Azure using Graph API and compare it with the list of users authenticated in Azure for the last 90 days you generated earlier.
$GrapUserUrl = 'https://graph.microsoft.com/v1.0/users'
$allusers=(Invoke-RestMethod -Headers @{Authorization = "Bearer $($token)"} -Uri $GrapUserUrl -Method Get).value
$allusers = $allusers | Select-Object @{Name="UPN"; Expression = {$_.userprincipalname.ToLower()}}
$activeusers = $alluserhistory|select UPN –Unique
Then you just have to compare the two lists. Thus, using a PowerShell script you can find inactive users and remove unused Microsoft 365/Azure AD licenses.
Export Azure AD User Sign-in Logs Using the Get-AzureADAuditSignInLogs Cmdlet
You can use the Get-AzureADAuditSignInLogs cmdlet from the AzureADPreview PowerShell module to get and export Azure AD/ Microsoft 365 sign-in audit logs. For some reason, there is no such cmdlet in the latest AzureAD for PowerShell module (apparently, Microsoft thinks that the Graph API is enough for us).
Install the AzureADPreview module to your computer:
Install-Module AzureADPreview –AllowClobber
Connect to your Azure tenant using AzureADPreview:
AzureADPreview\Connect-AzureAD
The following command will return information about the last 10 user sign-in events to Azure and Microsoft 365 apps:
Get-AzureADAuditSignInLogs -Filter "UserPrincipalName eq '[email protected]'" -Top 10 | select CreatedDateTime, UserPrincipalName, IsInteractive, AppDisplayName, IpAddress, TokenIssuerType, @{Name = 'DeviceOS'; Expression = {$_.DeviceDetail.OperatingSystem}}|ft
You can display statistics on user logins to Azure for the last 3 days and export them to a CSV file:
$SetDate = (Get-Date).AddDays(-3);
$SetDate = Get-Date($SetDate) -format yyyy-MM-dd
$array = Get-AzureADAuditSignInLogs -Filter "createdDateTime gt $SetDate" | select userDisplayName, userPrincipalName, appDisplayName, ipAddress, clientAppUsed, @{Name = 'DeviceOS'; Expression = {$_.DeviceDetail.OperatingSystem}},@{Name = 'Location'; Expression = {$_.Location.City}}
$array | Export-Csv "C:\PS\AzureUserSigninLogs.csv" –NoTypeInformation
12 comments
Excellent article; easy to follow as well!
‘Get-AzureADAuditSignInLogs’ is not recognized as the name of a cmdlet
Did you install the AzureADPreview module?
Install-Module AzureADPreview –AllowClobber
Different person answering, but yes, it is installed – v2..0.2.149
Also I get an error:
Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
At line:1 char:2
+ (Invoke-RestMethod -Headers @{Authorization = “Bearer $($token)”} -Ur …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Have you created a new Azure AD ( App registration) in your tenant, granted the API permissions to your Azure app, and replaced the values of the following variables in the script?
$ApplicationID
$TenatDomainName
$AccessSecret
Note – I was getting this when trying to use Powershell in the terminal.. I had to go to the launch button, type in powershell, then launch it from there.. There was an error about powershell core vs powershell desktop. HOURS of troubleshooting wasted on the powershell “blind grope”
is there a way to get the Device name (laptop name)? for a history of who logged into that device?
Is there a way to get more than 30 days of login data? I have not found a way yet.
Let me know if you find a way, i’m looking for same
Most M365 and supposedly E3 default to 30 days retention. E5 defaults to 90. That may be your issue.
I have seen some subscriptions with no Azure subscription only allow for 7 days.
Thank you!
I had a few questions.
Is it possible to change the CreatedDateTime Timezone from UTC?
Is it possible to split the Date and Time into it’s on columns on the export?
I will never understand why Microsoft has taken the path of most resistance with respect to some data. The Get-AzureADAuditSignInLogs is extremely cumbersome to use. Even if you get it to work, my understanding is it only returns data from the past 30 days. It returns a value called CreatedDateTime, which I would assume from the name refers to the time the account was created. However, the date is always today and users are listed multiple times. This is useless when attempting to determine what accounts are no longer actively used. Fortunately, I can use Get-ADUser to retrieve all the information I want exactly as I want it using a single command. Thank God we are a hybrid organization. I pity anybody who has a cloud only environment.