Track Failed User Sign-Ins Using Graph PowerShell

Monitoring failed sign-in attempts is crucial for maintaining the security of your Microsoft 365 environment. By tracking failed logins, administrators can identify potential security threats and take necessary actions to protect their organization. In this article, we will guide you through a PowerShell script that leverages Microsoft Graph to track failed user sign-ins and explain its components in detail.


Script to Track Failed User Sign-Ins

Here's a PowerShell script that connects to Microsoft Graph, retrieves sign-in logs for a specified period, and identifies users with failed sign-ins:

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "AuditLog.Read.All"

# Define the time range for sign-in logs (e.g. last 7 days)
$startTime = (Get-Date).AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endTime = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")

# Get sign-in logs for the specified time range
$signInLogs = Get-MgAuditLogSignIn -Filter "createdDateTime ge $startTime and createdDateTime le $endTime"

# Initialize an array to hold users with failed sign-ins
$failedSignInUsers = @()

# Loop through each sign-in log and check for failed sign-ins
foreach ($log in $signInLogs) {
    if ($log.Status.ErrorCode -ne 0) {
        $failedSignInUsers += [PSCustomObject]@{
            UserId            = $log.UserId
            UserPrincipalName = $log.UserPrincipalName
            SignInStatus      = $log.Status.ErrorCode
            FailureReason     = $log.Status.FailureReason
            Timestamp         = $log.CreatedDateTime
        }
    }
}

# Output the list of users with failed sign-ins
$failedSignInUsers | Format-Table -AutoSize

Script Output


Script Explanation

Connect to Microsoft Graph:

The script begins by establishing a connection to Microsoft Graph using the Connect-MgGraph cmdlet with the AuditLog.Read.All scope, which is necessary to read audit logs.

Connect-MgGraph -Scopes "AuditLog.Read.All"

Define Time Range:

The script defines a time range for the sign-in logs. In this example, we retrieve logs from the past 7 days.

# Define the time range for sign-in logs (e.g. last 7 days)
$startTime = (Get-Date).AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endTime = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")

Retrieve Sign-In Logs:

Using the Get-MgAuditLogSignIn cmdlet, the script fetches the sign-in logs within the specified time range.

# Get sign-in logs for the specified time range
$signInLogs = Get-MgAuditLogSignIn -Filter "createdDateTime ge $startTime and createdDateTime le $endTime"

Check for Failed Sign-Ins:

The script loops through each log entry and checks if the ErrorCode is not 0, which indicates a failed sign-in attempt.


# Loop through each sign-in log and check for failed sign-ins
foreach ($log in $signInLogs) {
   if ($log.Status.ErrorCode -ne 0) {
   $failedSignInUsers += [PSCustomObject]@{
   UserId            = $log.UserId
   UserPrincipalName = $log.UserPrincipalName
   SignInStatus      = $log.Status.ErrorCode
   FailureReason     = $log.Status.FailureReason
   Timestamp         = $log.CreatedDateTime
  }
 }
}

Store and Output Results:

Users with failed sign-ins are stored in an array and then outputted in a tabular format using Format-Table.

# Output the list of users with failed sign-ins
$failedSignInUsers | Format-Table -AutoSize

Further Enhancements

  • Email Notifications: Enhance the script to send email notifications to administrators when a user experiences a failed sign-in attempt.
  • Log to File: Modify the script to log failed sign-in details to a file for historical tracking and auditing purposes.
  • Additional Filters: Implement additional filters to narrow down the logs to specific users, IP addresses, or error codes.

Use Cases

  • Security Monitoring: Regularly monitor failed sign-ins to detect and respond to potential security threats.
  • Account Management: Identify accounts that might be targeted by brute-force attacks and enforce additional security measures.
  • Compliance: Maintain records of failed sign-in attempts for compliance and auditing purposes.

Possible Errors & Solutions

Error: Insufficient Permissions

Error: Get-MgAuditLogSignIn : Request Authorization failed. Status: 403 (Forbidden) ErrorCode: accessDenied

Solution: Ensure your account has the AuditLog.Read.All permission and that admin consent has been granted.

Error: Invalid Time Range

Error: Get-MgAuditLogSignIn : The specified time range is invalid

Solution: Verify the time range format and ensure the start time is before the end time.

Error: Empty Results

Error: The script runs successfully but returns no data.

Solution: Ensure there are sign-in activities within the specified time range and that you have the correct scopes and permissions.


Conclusion

Tracking failed user sign-ins using Microsoft Graph PowerShell is a powerful way to enhance your organization's security posture. By monitoring and responding to failed login attempts, administrators can proactively address potential security threats and ensure compliance with security policies. This script provides a solid foundation for identifying failed sign-ins and can be further customized to meet your specific requirements.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex