LDAP Directory Entry in .Net - not working with OU=Users - c#

I have the following code (C#):
(Tweaked from: http://www.eggheadcafe.com/conversation.aspx?messageid=31766061&threadid=31766050)
DirectorySearcher dseSearcher = new DirectorySearcher();
string rootDSE = dseSearcher.SearchRoot.Path;
DirectoryEntry rootDE = new DirectoryEntry(rootDSE);
string userDSE = rootDSE.Insert(7, "OU=Users,");
DirectoryEntry userDE = new DirectoryEntry(userDSE);
The rootDSE is created correctly, however, the user userDSE is unusable and throws "There is no such object on the server" exception if I attempt to use it.
The LDAP strings are as follows:
Root: LDAP://DC=company,DC=local
User: LDAP://OU=Users,DC=company,DC=local
I'm running on Vista as Admin, but need this to work on XP (Admin) as well.
I'm new to LDAP and Directory Management, so I'm stumbling around in the dark here. Any thoughts? Also - any articles to link too that could give me some insight into how it all works would be appreciated.

The first thing I would try as a test is to hardcode your desired path when you create a directory entry like so:
DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,DC=company,DC=local");
This will tell you pretty quick if this is an actual path in your Active Directory. I don't know what your AD looks like so I can't tell you if this is a valid path or not. Under your Active Directory Users and Computers MMC plugin, if this path is correct, then you should have your root domain, and a OU folder under the root called Users.
Paths are generated backwards in AD, so if your Users folder is under another OU off the root than it would be
DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,OU=<first OU folder>,DC=company,DC=local");
So your AD schema would look like:
Root
|
--><first OU folder>
|
-->Users
A great article on how to manage Active Directory in .NET:
HowTo: Do (Almost) Everything in Active Directory via C#
You might also want to research the System.DirectoryServices, System.DirectoryServices.ActiveDirectory, and the System.DirectoryServices.AccountManagement namespaces provided in the .Net 3.5 Framework. I believe System.DirectoryServices, and ActiveDirctory namespaces were available staring in .Net 1.1, and AccountManagement was introduced in .Net 3.5.
Microsoft Documentation - A lot of good links on how to use the namespace
Addendum:
To actually find a user in AD you will want to do the following:
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://DC=company,DC=local";
de.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user) (cn=" + username + "))";
SearchResult result = deSearch.FindOne();
if (result != null)
{
DirectoryEntry deUser = new DirectoryEntry(result.Path);
... do what ever you need to the deUser
deUser.Close();
}

This may seem silly and stupid, but the default tree setup in Active Directory is not OU=Users,dc=domain,dc=com but rather cn=Users,dc=domain,dc=com (Note the CN= not the OU= for Users.
It seems stupid since a container object (objectClass of cn) in AD cannot be a recipient of group policy, but for reasons I do not understand, that is the default. (actually I do understand, it is because containment for a CN is more similar to an NT domain than OU)
Gets almost everybody I meet, first time they try to LDAP bind/auth to AD.

As geoffc mentioned correctly, in Active Directory the "Users" under the domain is a container object rather than organizational unit object.
This results in a totally different LDAP path which is why you get the error message.
Try the following code and post if it fixes your issue:
// Replace the "company" and "com" with actual domain values...
DirectoryEntry de = new DirectoryEntry("LDAP://CN=Users,DC=company,DC=com");
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
// Set your other search params here

Related

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 ...
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.

How to query Active Directory B if application server is in Active Directory A

So heres my question. I have a Asp.net application with a form based authentication. I have users in my database but the users also has to be in the active directory.
The following code is for me to check if user is in the domain A
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://domainA.com";
de.AuthenticationType = AuthenticationTypes.None;
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(SAMAccountName=" + account + ")";
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
This code work fine. The problem is client is requesting that domain B should also be able to connect to the application. So created the following code:
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://domainB.com";
de.AuthenticationType = AuthenticationTypes.None;
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "(SAMAccountName=" + account + ")";
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
Since my server is in domainA this does not work. Is there a way for me to query domainB knowing that the server is in domainA? I found an article saying trust needs to be setup for domainA and B but this domains shouldnt be linked. Its only for this application that they need this functionality.
P.S. I might forgot to explain an important detail. domainA and B are not on the same network. But domainA can ping domainB
While trying samples against a foreign domain, I noticed that the foreign DC is giving the error message "The server is unavailable" when using the wrong authentication type. Please try:
de.User = #"DOMAINB\user";
de.Password = "YourPassword";
de.AuthenticationType = AuthenticationTypes.None;
Of course this results in an unsecured BASIC simple bind, which removes any encryption ADSI might offer. If this works, you should try a more secure authentication type that the server accepts.
An alternative might be using the "System.DirectoryServices.Protocols"-namespace which offers a more lightweight approach for AD access. I can provide you with a sample I you want to go in this direction.
You will need to provide credentials that have permission to query AD on domain B.
var de = new DirectoryEntry("LDAP://domainB.com", "Username", "Password");
var search = new DirectorySearcher(de);

Problems with LDAP

I am having trouble with LDAP. Now I use this code:
DirectoryEntry ldapConnection = new DirectoryEntry("LDAPS://*******.com:636", "User#bloom.local", "Password");
ldapConnection.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
DirectorySearcher search = new DirectorySearcher(ldapConnection);
var result = search.Filter = "(objectClass=*)";
search.FindAll();
I spent a large number of experiments, but never received:
Unknown error (0x80005000)
or
The server is not operational.
My property in the softerra LDAP Administrator:
The problem is that the simple authentication mechanism requires an LDAP distinguished name (DN) and you provided just a user name. At least, this is what your screenshot shows.
The DN of the administrator is likely something like cn=Administrator,cn=Users,dc=bloom,dc=local.
Also, I would probably steer away from using the administrator credentials in production. It is much more preferable to create an account with the right privileges.

How to check if address lists exist in Active Directory?

I need to check if All Global Address Lists, All Address List and All System Address Lists exist in Active Directory before get all item from them.
Could you give me some advices or article that I can solve my problem?
Thanks.
Address Lists are part of Exchange functionality not Active Directory which is what I think people are confused about.
Anyway, Address List data is stored in the Active Directory Configuration context under:
CN=Address Lists Container,CN=<EXCHANGE ORGANIZATION NAME>,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=<DEFAULT NAMING CONTEXT>
You can use ADSIEdit to view the information.
In C# you can use an LDAP query to retrieve information for existing Address Lists.
Edit: Something like this:
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
DirectoryEntry configContainer = new DirectoryEntry("LDAP://" + rootDSE.Properties["configurationNamingContext"].Value);
DirectorySearcher configSearcher = new DirectorySearcher(configContainer);
configSearcher.Filter = "(&(objectClass=addressBookContainer))";
configSearcher.PropertiesToLoad.Add("displayName");
configSearcher.PageSize = 10000;
configSearcher.SearchScope = SearchScope.Subtree;
SearchResultCollection results = configSearcher.FindAll();

credential cache

Does anyone know how to use the credential cache or network credential to get the user's personal info from the Active Directory using C# or VB? I need to get personal info such as name, telephone ID and so on.
See the System.DirectoryServices class documentation.
DirectorySearcher ds = new DirectorySearcher("LDAP://DC=test,dc=com");
ds.Filter = String.Format("&(samaccountname={0})(objectcategory=user)",Environment.Username);
ds.PropertiesToLoad.Add("telephoneNumber");
ds.PropertiesToLoad.Add("Name");
// add all properties here
DirectoryEntry de = ds.FindOne();
By default a user will have sufficent rights to read their own personal details.
If they do not you may need to use Delegation on your directory to allow SELF read access to extra attributes

Categories