Active Directory LDAP - Lock User Account
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..
UserPri开发者_如何学编程ncipal 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();
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.
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();
}
}
This code will work to lock a user in AD
///
/// Locks a user account
///
/// The name of the user whose account you want to unlock
///
/// This actually trys to log the user in with a wrong password.
/// This in turn will lock the user out
///
public void LockAccount(string userName)
{
DirectoryEntry user = GetUser(userName);
string path = user.Path;
string badPassword = "SomeBadPassword";
int maxLoginAttempts = 10;
for (int i = 0; i < maxLoginAttempts; i++)
{
try
{
new DirectoryEntry(path, userName, badPassword).RefreshCache();
}
catch (Exception e)
{
}
}
user.Close();
}
There is a good example here http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#45
using userflag property we can get the user locked status here is my answer
entryPC is object for the DirectoryEntry here we pass the entry path of active directory
public bool IsLocked(DirectoryEntry entryPC)
{
if (entryPC.NativeGuid == null)
{
return false;
}
int flags = (int)entryPC.Properties["UserFlags"].Value;
bool check = Convert.ToBoolean(flags & 0x0010);
if (Convert.ToBoolean(flags & 0x0010))
{
return true;
}
else
{
return false;
}
}
精彩评论