views:

294

answers:

2

What is the best way to use System.DirectoryServices.AccountManagement to lock an Active Directory user object? I'm able to determine if an account is locked using..

UserPrincipal principal = new UserPrincipal(context);
bool locked = principal.IsAccountLockedOut();

How do I lock the account? Is there an alternative to doing something like this...

UserPrincipal principal = new UserPrincipal(context);
DirectoryEntry entry = (DirectoryEntry)principal.GetUnderlyingObject();

int val = (int)entry.Properties["userAccountControl"].Value;

entry.Properties["userAccountControl"].Value = val | 0x0010;
entry.CommitChanges();
A: 

The lock attribute is read-only by definition and here is why:

The definition for this attribute will go something like: "automatically lock user account when invalid password is provided several times" (how many times? I guess this is set in the GPO)

Giving developers a way to change this attribute will conflict with the above definition... so you shouldn't set this value and I think AD security mechanism will block you from doing this.

You can however enable\disable the user which I think is more close to what you want.

Hope this helps.

Joshua
A: 

CodeProject's Everything AD article has some sample code on unlocking an account. I'm not certain that this is the property that would give you what you're looking for.

public void Unlock(string userDn)
{
    try
    {
        DirectoryEntry uEntry = new DirectoryEntry(userDn);
        uEntry.Properties["LockOutTime"].Value = 0; //unlock account

        uEntry.CommitChanges(); //may not be needed but adding it anyways

        uEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingWith --> E.Message.ToString();

    }
}
p.campbell