Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlocking user Account

I am trying to set properties to unlock User accounts in AD and I am using the following code; the problem is that de does not contain userAccountControl and the code fails.

I can get the value of userAccountControl by using DirectorySearcher but that does not help me in setting the property using de. Could anyone please help me? Thanks in advance

String m_Path = "LDAP://" + distinguishedName;

using (DirectoryEntry de = new DirectoryEntry(m_Path))
{
   if (de.Contains("userAccountControl")
   {
      int m_Val  = (int)de.Properties["userAccountControl"][0].Value;
      de.Properties["userAccountControl"].Value = m_Val | 0x0001
      de.CommitChanges;
   }
}
like image 389
KSM Avatar asked Jan 20 '23 00:01

KSM


1 Answers

I would think you need to check whether de.Properties contains a value of userAccountControl!

string ldapPath = "LDAP://" + distinguishedName;

using(DirectoryEntry de = new DirectoryEntry(ldapPath))
{
   // check to see if we have "userAccountControl" in the **properties** of de
   if(de.Properties.Contains("userAccountControl")
   {
      int m_Val  = (int)de.Properties["userAccountControl"][0].Value ;
      de.Properties["userAccountControl"].Value = m_Val | 0x0001;

      de.CommitChanges();
   }
}

Also, if you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find and manipulate users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // unlock user
   user.UnlockAccount();
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

like image 94
marc_s Avatar answered Feb 09 '23 01:02

marc_s