Expiring AAD Guests

Maho bay, St John, USVI

The guest user feature in Azure AD is a critical part of collaborating with B2B partners, permitting them to work with your users on shared documents in OneDrive and SharePoint as well as communicate via Teams.

If you’re going to permit guest users on your tenancy, it’s important that you have a strategy for offboarding them when access is no longer required. After all, offboarding is not something employees are likely to manage in a predictable manner. What’s needed are one or more backstops to prevent unintended access by a third party.

Part of our solution is to use Azure AD Access Reviews, a feature of Azure AD Premium P2. These ask group owners to validate and attest that users should continue to have access to company resources.

Our backstop behind that is to remove guest user accounts that are inactive. While this could be done manually, a newish feature exposed in the beta of the Microsoft Graph API permits us to query for users by last sign-in time.

Given this feature it’s pretty simple to write a script, using the PowerShell SDK, that removes guest users that haven’t signed in for a given (“XXX” below) period of time:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
$mesg = Connect-MgGraph -ClientID $Conn.ApplicationID `
    -TenantId $Conn.TenantID `
    -CertificateThumbprint $Conn.CertificateThumbprint `
    -ErrorAction stop

Select-MgProfile -Name "beta"  

$before = (get-date).AddDays(-XXX).toString('yyyy-MM-dd')

$users = Get-MgUser -Filter "signInActivity/lastSignInDateTime le $before"  

$users | where UserType -eq "Guest" | foreach {                  
    remove-mguser -UserId $_.Id
    Write-Output "Deleted $($_.DisplayName)"
}

$mesg = disconnect-mggraph

We run this script on a schedule via Azure Automation. Note the switch to the beta API on line 7. The other thing of note is that the filter query doesn’t seem to like userType anded with the signin date test: so we filter out directory members using a where statement ahead of the foreach.

Hope you find it helpful. Happy Thanksgiving!