Do you have an on-premises Active Directory environment syncing to Azure Active Directory? If so, you may have run across a frustrating problem: An on-premises AD user license has expired but that user can still access resources on Azure AD. As long as you’re on a Windows 10 computer with the Remote Server Administration Tools and the Azure PowerShell module installed, you can remedy this security risk by finding all expired AD accounts and revoking them.
1. Find Expired Accounts of Your Users
The easiest way to find expired AD user accounts is by using the Search-AdAccount PowerShell cmdlet. Open up a PowerShell console and run Search-AdAccount, limiting the scope to only expired user accounts: $expiredUsers = Search-ADAccount -AccountExpired -UsersOnly
2. Disable the Users' Expired Accounts
Create a PowerShell “foreach loop” to disable each expired user account found. The following code passes each user account saved in $expiredUsers to the Disable-AdAccount cmdlet and attempts to disable each one: for each ($user in $expiredusers): {$user | Disable-ADAccount}
If you’d rather not be prompted each time when disabling a user, use the parameter and value -Confirm:$false.
3. Revoke Azure Active Directory User Refresh Tokens
Using the foreach loop created earlier, first add another step inside of the loop to find the on-premises AD account’s associated Azure AD account using the Get-AzADUser cmdlet. Once the associated Azure AD account is found, pass it to the Revoke-AzureADUserAllRefreshToken cmdlet. Here is a script you can use to bring all of these instructions together:
$expiredUsers = Search-ADAccount -AccountExpired -UsersOnly
foreach ($user in $expiredusers) {$user | Disable-ADAccount | Get-AzADUser -ObjectId
$user.UserPrincipalName | Revoke-AzureADUserAllRefreshToken}
4. Create a Scheduled Task
You now have a script that finds all expired, on-premises AD user accounts; finds each account’s Azure AD account; and revokes each account’s refresh token. Running this action once is great — but in an active environment, user accounts will generate more refresh tokens. Be sure to keep up to date by including this script in a Windows scheduled task or other tool to run these steps regularly.