Disable and revoke Azure AD tokens from expired AD users


If you have an environment on-premises and are starting to take advantage of the cloud, then there’s a lot to be aware of. One big thing to take notice of is that Azure AD does not respect user expired state in AD. When logging on to Office 365 services outside of ADFS with CloudNative Auth, this becomes a huge problem. Even though the user is expired in AD, it might be able to log on to your cloud services. Therefore, I have written a script that you should run on a daily schedule, that disables expired users in AD and revoke any Azure AD tokens the user might have.

#"Password!" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "D:\temp\PassordUserExpireScript.txt"
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "[email protected]", (Get-Content "d:\temp\PassordUserExpireScript.txt" | ConvertTo-SecureString)
#Gets all users thats enabled and have a expiration date.
$Users = Get-ADUser -Filter * -Properties AccountExpirationDate | select AccountExpirationDate,Enabled,UserPRincipalName,samaccountname,name | Where-Object{$_.Enabled -eq $true -and $_.AccountExpirationDate}
#Todays date.
$today = Get-Date -Format dd/MM/yyyy
foreach($User in $users){
($user.AccountExpirationDate | get-date -Format dd/MM/yyyy)
#If user have expired we disable it and revoke any Azure AD tokens.
If((($user.AccountExpirationDate | get-date -Format dd/MM/yyyy) -eq $today) -or (($user.AccountExpirationDate | get-date -Format dd/MM/yyyy) -lt $today)){
Disable-ADAccount -Identity $user.samaccountname
Get-AzureADUser -ObjectId $user.UserPRincipalName | Revoke-AzureADUserAllRefreshToken


Script here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s