Detect if an Active Directory user account is locked using LDAP in Python Detect if an Active Directory user account is locked using LDAP in Python python python

Detect if an Active Directory user account is locked using LDAP in Python


A value of zero in lockoutTime means it's not locked out. So, you should try this.

(&(objectClass=user)(!lockoutTime=0)) 

Actually, the above query is still not 100% correct. If you read the fine print from MSDN, Microsoft is suggesting you to add the Lockout-Time attribute to the Lockout-Duration attribute and then compare it with the current time. That's because there is such a thing called lockout duration. Once the lockout duration passes, the user is unlocked automatically. Zero in Lockout-Duration means the account is locked forever until the administrator unlock it.

See this MSDN article

This attribute value is only reset when the account is logged onto successfully. This means that this value may be non zero, yet the account is not locked out. To accurately determine if the account is locked out, you must add the Lockout-Duration to this time and compare the result to the current time, accounting for local time zones and daylight savings time.


lockoutTime is a <not set> attribute so the easiest way is to use:

(&(objectClass=user)(lockoutDuration=*))) 

for the non-empty entries.

Update:

However, this value is also set when the password expires, password needs to change etc.

So it needs to be filtered by:

UserPrincipal userPrincipal = new UserPrincipal(context);bool isLocked = userPrincipal.IsAccountLockedOut();

to get the cases where the user is locked out because they violated the password policy e.g incorrectly entered the password 5 times.


In addition, I found that lockoutTime is not guaranteed for all users in AD (at least in our configuration), but will be created upon reaching the number of failed lockout attempts. So in checking for locked accounts, checking for None or an equivalent will be required as well.