Search code examples
c#active-directoryldap

Read and write "uid" property in Active Directory from a desktop application in .NET


I'm trying to manipulate the uid property of AD to store some extra info but I'm getting an UnauthorizedAccessException when using this code:

DirectoryEntry de = new DirectoryEntry("LDAP://somedomain.net");
DirectorySearcher ds = new DirectorySearcher(de);

ds.Filter = "(&(objectClass=user)(|(cn=" + username + ")(sAMAccountName=" + username + ")))";
ds.PropertiesToLoad.Add("uid");

SearchResult? rs = ds.FindOne();

if (rs != null)
{
    DirectoryEntry de = rs.GetDirectoryEntry();

    if (rs.Properties.Contains("uid")) 
        de.Properties["uid"].Value = "123456";
    else 
        de.Properties["uid"].Add("123456");

    de.CommitChanges();
}

I have no trouble when I manipulate the postalCode property instead of uid using the same code, so I'm really lost. Don't I have enough privileges on the domain to write to the uid property? Or do I have to access it in a different way?

EDIT: it seems I can't access postalCode property of another user other than mine. I suppose that I have to login with a domain administrator account or impersonate it in some way, but I have no idea how to do that ...


Solution

  • It seems I can't access "postalCode" property of another user other than mine. I supose that I have to login with a domain administrator account or impersonate it in some way, but I have no idea of how...

    The DirectoryEntry class constructor takes explicit credentials for exactly this kind of scenario:

    DirectoryEntry de = new DirectoryEntry("LDAP://somedomain.net/", "SOMEDOMAIN\Administrator", "sup3rs3cr3t");
    

    Rather than using a Domain Admin account, I'd strongly suggest delegating the minimum required access permissions on the target accounts to a service account the credentials of which you can then use in your program - this way you limit the potential impact from someone stealing the credentials.