I am very new to the LDAP and Active Directory integration portion. Although I successfully configured my local machine to access Active Directory domain controller, when I deployed it on one of our server neither through IP address of the domain nor through domain name it was accessible.
My website is in ASP.NET C#.
It was getting this error:
The specified domain either does not exist or could not be contacted.
My method written to access AD is here:
private SearchResultCollection sResults { get; set; }
sResults = null;
public void SearchByUsername(string username)
{
try
{
// initiate a directory entry
private const string ldapPath = "LDAP://192.168.0.190/OU=Domain Users,DC=mydomain,DC=net"
dEntry = new DirectoryEntry(ldapPath);
dSearcher = new DirectorySearcher(dEntry);
dSearcher.Filter = "(&(objectClass=user)(sAMAccountname= " + username + "))";
performSearch();
getValues();
}
catch (Exception)
{
throw;
}
}
private void performSearch()
{
// perform search in Active Directory
sResults = dSearcher.FindAll();
}
private void getValues()
{
// loop through results of search
foreach (SearchResult sResult in sResults)
{
Employee emp = new Employee();
emp.CN = getProperty(sResult, "cn");
emp.FirstName = getProperty(sResult, "givenName");
emp.LastName = getProperty(sResult, "sn");
emp.Username = getProperty(sResult, "sAMAccountname");
emp.Email = getProperty(sResult, "mail");
Employees.Add(emp);
}
}
Above method works very well on my local machine both with IP address and domain name. Server where I am trying this to work is Windows Server 2012 R2.
I ran command nltest /dclist:mydomain.net and made sure that the server is within the domain as it returned me details. i.e. DC name, IP address, domain name.
Is there any syntactical issue I have run into? OR is it related to configuration issue like DNS ?
Also, like to mention as I tried searching about this on www.serverfault.com but couldn't gather much details.
Please suggest me direction.
Finally things seemed working out.
Earlier I mentioned that I made sure that the machine I am working on is in the domain but things were slightly different there. The machine I am trying to make things work is not actually in the domain but in the workgroup.
Below two Netdom commands helped me identifying this situation.
netdom verify - with this command it is found that machine hasn't joined domain.
netdom join - with this command, was able to join machine to network domain.
Reference: https://technet.microsoft.com/en-us/library/cc772217.aspx
Once it is in domain, Active Directory became immediately accessible.
Related
Question first, explanation later: How can I get the GC server for any given LDAP server?
To understand my needs, let me explain:
I had to extend Henning Krause's ExchangeAddressListService (I am not sure whether I should/may c'n'p all of Henning's code into this post?) to get useful debug output:
private DirectoryEntry GetDirectoryEntry(string path, string protocol)
{
var ldapPath = string.IsNullOrEmpty(path) ? string.Format("{0}:", protocol) : string.Format("{0}://{1}", protocol, path);
dbg.Add("Getting DirectoryEntry for path " + ldapPath);
return new DirectoryEntry(ldapPath);
}
public ActiveDirectoryConnection(Debug dbg)
{
this.dbg = dbg;
}
and to allow for selection of a certain domain:
internal AddressList(string path, ActiveDirectoryConnection connection, string domain)
{
_Path = path;
_Connection = connection;
_Domain = domain;
}
...
private IEnumerable<AddressList> GetAddressLists(string containerName)
{
string exchangeRootPath;
using (var root = _Connection.GetLdapDirectoryEntry(_Domain+"/RootDSE"))
...
foreach (SearchResult addressBook in searchResultCollection)
{
yield return
new AddressList((string)addressBook.Properties["distinguishedName"][0], _Connection, _Domain);
}
...
}
Now I have a problem with the domain because it seems as if for some domains SOMEDOMAIN the Global Catalog cannot be accessed via GC://SOMEDOMAIN. This is my code I use:
var domain = User.Identity.Name.Split('\\')[0]; // SOMEDOMAIN\SomeUser -> Domain is SOMEDOMAIN
dbg.Add("User NETBIOS domain is "+domain);
AddressListService addressListService = new ExchangeAddressListService(connection,domain);
IEnumerable<AddressList> addressLists = addressListService.GetGlobalAddressLists();
AddressList addressList = addressLists.First()
try {
IEnumerable<SearchResult> searchResults = addressList.GetMembers("displayName", "distinguishedname", "mail")
} catch(Exception e) {
dbg.Add("Error in GetMembers: "+e.Message);
return new AjaxAnswer(dbg.Flush());
}
It produces the error log:
User NETBIOS domain is SOMEDOMAIN
Getting DirectoryEntry for path LDAP://SOMEDOMAIN/RootDSE
Getting DirectoryEntry for path LDAP://CN=Microsoft Exchange, CN=Services, CN=Configuration,DC=somedomain,DC=net
Getting DirectoryEntry for path LDAP://CN=All Global Address Lists,CN=Address Lists Container, CN=MYMAIL,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=somedomain,DC=net
Getting DirectoryEntry for path LDAP://CN=Default Global Address List,CN=All Global Address Lists,CN=Address Lists Container,CN=MYMAIL,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=somedomain,DC=net
Getting DirectoryEntry for path GC://SOMEDOMAIN
Error in GetMembers: The server is not operational.
Not all DC are GC. So GC://SOMEDOMAIN may fail if SOMEDOMAIN is not a GC.
In my project, I use the DsGetDcName Win32 function to discover the GC.
Details of DsGetDcName function:
http://msdn.microsoft.com/en-us/library/ms675983%28v=vs.85%29.aspx
See below for how to pinvoke the call:
http://www.pinvoke.net/default.aspx/netapi32.dsgetdcname
As I know System.DirectoryServices.ActiveDirectory also provide classes to handle GC.
e.g. Forest.GlobalCatalogs
I already use the DsGetDcName function, so never tried this before.
I am developing a web application that authenticate the user against an Active Directory Server. Now if I run my code from the development PC under the domain of that AD server, my code is running smoothly. We need to run the code from a totally different network using VPN and here the development PC is not into that AD. I am getting following error while trying to access the AD server.
The specified domain either does not exist or could not be contacted.
My VPN is working fine. I could access remote desktops using this VPN. I know a little tweak is required to solve the problem but could not find it. I went through following links but could not find any solution.
Domain Authentication from .NET Client over VPN
How do I get the Current User identity for a VPN user in a Windows forms app?
Following is my settings in web.config
<appSettings>
<add key="LDAPPath" value="LDAP://DC=MYSERVER,DC=COM" />
<add key="ADGroupName" value="Analyst"/>
</appSettings>
and here is my code
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;
public LdapAuthentication()
{
_path = System.Configuration.ConfigurationManager.AppSettings["LDAPPath"].ToString();
}
public bool IsAuthenticated(string username, string pwd)
{
try
{
DirectoryEntry entry = new DirectoryEntry(_path, username, pwd);
entry.Path = _path;
entry.Username = username;
entry.Password = pwd;
// Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
return true;
}
}
Any help would be appreciated. Thank you.
I had a similar, though simpler problem. I had success in using the following code:
private bool DoLogin(string userName, string password)
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DomainName.com")) {
bool isValid = pc.ValidateCredentials(userName, password);
if (isValid) {
// authenticated
...
return true;
}
else {
// invalid credentials
...
return false;
}
}
}
Using the ".com" at the end of the domain name was important to get it working for me. Without it I got the same symptoms you describe.
I've just been grappling with this for a couple of hours. No problems when on the network, lots of problems when connecting via VPN. It seems that when you are connecting over a VPN, the 'connection string' for DirectoryEntry has to be a lot more precise. I finally got it to work with an LDAP address/connection string like this:
LDAP://ip_of_primary_domain_controller/fully qualified path of the container object where the binding user is located
So for example something like this worked for me:
DirectoryEntry directoryEntry = new DirectoryEntry(
"LDAP://192.168.0.20/OU=Service Accounts,OU=Admin Accounts,DC=myserver,DC=com",
"username#myserver.com", "password");
... where "username#myserver.com" is located in OU=Service Accounts,OU=Admin Accounts,DC=myserver,DC=com. If you use SysInternals ADExplorer (or similar) to search for your username, it will tell you the correct fully qualified path for the container.
See here for a long answer about exactly whats should be in the 'connection string': https://serverfault.com/a/130556
I have a fairly odd requirement to be able to impersonate a user, when I'm already impersonating another, using C#.
I'm writing an app to allow the management of Active Directory users. This app will provide the ability for anyone in the company to view and maintain certain details about themselves (some of which will not actually be saved to Active Directory, but some of which will), for managers to be able to view and maintain details about their team, and for HR to be able to view and maintain details about anyone.
For obvious reasons I don't want to develop or test this against the live domain. We have recently ported all users over to this domain from another domain, which means I can actually test against the old domain without affecting anything. However, to enable me to do this I have to impersonate my old account on the old domain, which I do on loading the application.
Although for me everything will work fine as I'm setup as a domain admin, going forward obviously not all users will be domain admins, and won't be able to write to AD under their own account, and therefore we have another domain admin user setup specifically for this application, whenever data needs to be saved to AD that user is impersonated. This was working great before when I was testing against an Active Directory I'd setup on a virtual machine because I was logging onto the local domain, however that didn't allow me to step through the code in Visual Studio so debugging was slow, and hence I've stopped using that virtual machine and am using this old domain. Now I'm already impersonating another user (i.e. my old domain account), when it then tries to impersonate the domain admin user it fails with an "System.Security.SecurityException: Access is denied." exception. The line this fails on is just writing out some debugging information using "WindowsIdentity.GetCurrent().Name".
If I change my code so I'm actually logging in using the new domain admin rather than my old account, the first time it goes through it logs in successfully (so the credentials are correct), however when it then goes through and tries to do the same again to write to AD it fails with the above exception. Therefore I think it must be a problem with trying to do a nested impersonate.
Is it possible to do a nested impersonate?
Below is the code I'm using:
private static WindowsImpersonationContext ImpersonateUser(out string result, string sUsername,
string sDomain, string sPassword)
{
// initialize tokens
var pExistingTokenHandle = new IntPtr(0);
var pDuplicateTokenHandle = new IntPtr(0);
// if domain name was blank, assume local machine
if (sDomain == "")
{
sDomain = Environment.MachineName;
}
try
{
result = null;
const int logon32ProviderDefault = 0;
// create token
const int logon32LogonInteractive = 2;
// get handle to token
var bImpersonated = LogonUser(sUsername, sDomain, sPassword,
logon32LogonInteractive,
logon32ProviderDefault,
ref pExistingTokenHandle);
// did impersonation fail?
if (!bImpersonated)
{
var nErrorCode = Marshal.GetLastWin32Error();
result = "LogonUser() failed with error code: " + nErrorCode + "\r\n";
}
// Get identity before impersonation
result += string.Format("Before impersonation: {0}\r\n", WindowsIdentity.GetCurrent().Name);
var bRetVal = DuplicateToken(pExistingTokenHandle, (int)SecurityImpersonationLevel.SecurityImpersonation,
ref pDuplicateTokenHandle);
// did DuplicateToken fail?
if (bRetVal)
{
// create new identity using new primary token
var newId = new WindowsIdentity(pDuplicateTokenHandle);
var impersonatedUser = newId.Impersonate();
// check the identity after impersonation
result += "After impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
return impersonatedUser;
}
else
{
var nErrorCode = Marshal.GetLastWin32Error();
CloseHandle(pExistingTokenHandle); // close existing handle
result += "DuplicateToken() failed with error code: " + nErrorCode + "\r\n";
return null;
}
}
finally
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
{
CloseHandle(pExistingTokenHandle);
}
if (pDuplicateTokenHandle != IntPtr.Zero)
{
CloseHandle(pDuplicateTokenHandle);
}
}
}
When this is called for the nested impersonation which fails, "bImpersonated" is actually "true", as is bRetVal, which suggests its worked, however when it gets to "WindowsIdentity.GetCurrent().Name" it fails with the exception above.
I hope this makes sense, and would appreciate any assistance.
This is similar to, but not a dupe of, this question - however, where it sought information on manually joining a server to a domain (and was rightly redirected) I am looking for help with some code that programmatically joins a machine to a domain.
The scenario is that we have a launcher service that instantiates Amazon EC2 Server2008R1 VMs, optionally passing a Machine Name in through the User-Data stream. A process is baked into our images that checks User-Data for a name on bootup - If none is present then the VM remains outside of our Cloud domain, but if the name is present then the machine is renamed as specified and auto-joined to the domain.
Here's the problem - if I run this process manually any time after instance start, it works exactly as described; the machine name is changed, and the VM is joined to the domain (we force a restart to make this happen).
However, when running as a Scheduled Task (triggered on startup) the machine rename happens as expected, but the subsequent call to JoinDomainOrWorkgroup (see below) picks-up the old randomised machine name given to the VM by EC2 instead of the new name it has just been assigned.
This results in a WMI return code of 8525, we get a disconnected misnamed entry in the AD repository (of that randomised name) and the machine is not joined to the domain. The VM then restarts, and a second pass through the startup process (abnormally triggered because there is content in User-Data but the machine is not yet in the domain) executes all the same steps and succeeds.
It looks like the machine name is set in the first pass but not 'finalised', and JoinDomainOrWorkgroup still sees the original name. On the second pass, the machine name is already set properly, and so JoinDomainOrWorkgroup works as expected. Quite why the process behaves this way during startup, but works perfectly when run manually on an already-started VM, is I think the nub of the problem.
I've tried inserting a delay between the rename and join steps in case the call to JoinDomainOrWorkgroup was happening before the rename was finalised behind the scenes, but this hasn't helped - and I didn't really expect it to, since the whole process works perfectly when run manually. So it's probably a combination of a subtle difference in machine state during bootup and something silly in the code.
Maybe using System.Environment.MachineName in the SetDomainMembership method is inadvisable? But it stil fails even if I pass the new name in as a string as I do for SetMachineName. So I'm stumped.
Here's the WMI code that renames the machine:
/// <summary>
/// Set Machine Name
/// </summary>
public static bool SetMachineName(string newName)
{
_lh.Log(LogHandler.LogType.Debug, string.Format("Setting Machine Name to '{0}'...", newName));
// Invoke WMI to populate the machine name
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
{
ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
inputArgs["Name"] = newName;
// Set the name
ManagementBaseObject outParams = wmiObject.InvokeMethod("Rename", inputArgs, null);
// Weird WMI shennanigans to get a return code (is there no better way to do this??)
uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
if (ret == 0)
{
// It worked
return true;
}
else
{
// It didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to change Machine Name from '{0}' to '{1}'", System.Environment.MachineName, newName));
return false;
}
}
}
And here's the WMI code that joins it to the domain:
/// <summary>
/// Set domain membership
/// </summary>
public static bool SetDomainMembership()
{
_lh.Log(LogHandler.LogType.Debug, string.Format("Setting domain membership of '{0}' to '{1}'...", System.Environment.MachineName, _targetDomain));
// Invoke WMI to join the domain
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
{
try
{
// Obtain in-parameters for the method
ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup");
inParams["Name"] = "*****";
inParams["Password"] = "*****";
inParams["UserName"] = "*****";
inParams["FJoinOptions"] = 3; // Magic number: 3 = join to domain and create computer account
// Execute the method and obtain the return values.
ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
_lh.Log(LogHandler.LogType.Debug, string.Format("JoinDomainOrWorkgroup return code: '{0}'", outParams["ReturnValue"]));
// Did it work? ** disabled so we restart later even if it fails
//uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
//if (ret != 0)
//{
// // Nope
// _lh.Log(LogHandler.LogType.Fatal, string.Format("JoinDomainOrWorkgroup failed with return code: '{0}'", outParams["ReturnValue"]));
// return false;
//}
return true;
}
catch (ManagementException e)
{
// It didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to join domain '{0}'", _targetDomain), e);
return false;
}
}
}
Apologies if this code looks mind-numbingly stupid - I'm new to WMI, and this is largely cribbed from examples I've found on the interwebs; if there's a smarter/neater way to do this then by all means demonstrate. If you can cure the problem at the same time, bonus points!
OK, here it is.
Firstly, the order of the fields in System Properties is a little misleading - you see Machine Name first, and Domain/Workgroup below that. This subconsciously affected my thinking, and meant my code copied that ordering by trying to set the name first, and then join the machine to the domain. Whilst this does work under some circumstances, it's not consistent or reliable. So the biggest lesson learned here is...
Join the domain first - then change
the machine name.
Yep, that's actually all there is to it. After numerous test iterations, it finally dawned on me that it might work better if I tried it this way around. I tripped-up on the change of name on my first pass, but quickly realised that it was still using the local system credentials - but now that the machine was joined to the domain at this point, it needed the same domain credentials as were used to join the domain itself. A fast bit of code-tweaking later, and we now have a consistently-reliable WMI routine that joins the domain and then changes the name.
It might not be the neatest implementation (feel free to comment on improvements) but it works. Enjoy.
/// <summary>
/// Join domain and set Machine Name
/// </summary>
public static bool JoinAndSetName(string newName)
{
_lh.Log(LogHandler.LogType.Debug, string.Format("Joining domain and changing Machine Name from '{0}' to '{1}'...", Environment.MachineName, newName));
// Get WMI object for this machine
using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + Environment.MachineName + "'")))
{
try
{
// Obtain in-parameters for the method
ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup");
inParams["Name"] = "domain_name";
inParams["Password"] = "domain_account_password";
inParams["UserName"] = "domain_account";
inParams["FJoinOptions"] = 3; // Magic number: 3 = join to domain and create computer account
_lh.Log(LogHandler.LogType.Debug, string.Format("Joining machine to domain under name '{0}'...", inParams["Name"]));
// Execute the method and obtain the return values.
ManagementBaseObject joinParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);
_lh.Log(LogHandler.LogType.Debug, string.Format("JoinDomainOrWorkgroup return code: '{0}'", joinParams["ReturnValue"]));
// Did it work?
if ((uint)(joinParams.Properties["ReturnValue"].Value) != 0)
{
// Join to domain didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("JoinDomainOrWorkgroup failed with return code: '{0}'", joinParams["ReturnValue"]));
return false;
}
}
catch (ManagementException e)
{
// Join to domain didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to join domain '{0}'", _targetDomain), e);
return false;
}
// Join to domain worked - now change name
ManagementBaseObject inputArgs = wmiObject.GetMethodParameters("Rename");
inputArgs["Name"] = newName;
inputArgs["Password"] = "domain_account_password";
inputArgs["UserName"] = "domain_account";
// Set the name
ManagementBaseObject nameParams = wmiObject.InvokeMethod("Rename", inputArgs, null);
_lh.Log(LogHandler.LogType.Debug, string.Format("Machine Rename return code: '{0}'", nameParams["ReturnValue"]));
if ((uint)(nameParams.Properties["ReturnValue"].Value) != 0)
{
// Name change didn't work
_lh.Log(LogHandler.LogType.Fatal, string.Format("Unable to change Machine Name from '{0}' to '{1}'", Environment.MachineName, newName));
return false;
}
// All ok
return true;
}
}
Ok little update after all these years if somebody would need it.
WMI does not contain JoinDomain anymore only workgroup (WIN 10, Build 1909). You can use netapi32.dll
More info here:
https://learn.microsoft.com/en-us/windows/win32/api/lmjoin/nf-lmjoin-netjoindomain
Little fast example:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
static extern uint NetJoinDomain(
string lpServer,
string lpDomain,
string lpAccountOU,
string lpAccount,
string lpPassword,
JoinOptions NameType);
[Flags]
enum JoinOptions
{
NETSETUP_JOIN_DOMAIN = 0x00000001,
NETSETUP_ACCT_CREATE = 0x00000002,
NETSETUP_ACCT_DELETE = 0x00000004,
NETSETUP_WIN9X_UPGRADE = 0x00000010,
NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020,
NETSETUP_JOIN_UNSECURE = 0x00000040,
NETSETUP_MACHINE_PWD_PASSED = 0x00000080,
NETSETUP_DEFER_SPN_SET = 0x10000000
}
public static uint domainjoin(string server, string domain, string OU, string account, string password)
{
try
{
uint value1 = NetJoinDomain(server, domain, OU, account, password, (JoinOptions.NETSETUP_JOIN_DOMAIN | JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED | JoinOptions.NETSETUP_ACCT_CREATE));
return value1;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return 11;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var succes = domainjoin(null, "mydomain.local", null, "administrator", "UltraSecretPasword");
MessageBox.Show(succes.ToString());
}
}
I'm attempting to query AD in an ASP.Net (4.0) application that is running on Windows Server 2008 R2 (IIS7 installed). (It also fails when running as a 2.0 application as well)
This is nothing new for me, as I've done this many times before. I wrote a small ASP.Net program that runs fine on my own machine (Windows XP with IIS6), but fails when run on the 2008 box.
(The result is that you see a list of groups the user is a member of in a textbox)
(on button_click)
var userName = txtUserName.Text;
if (userName.Trim().Length == 0)
{
txtResults.Text = "-- MISSING USER NAME --";
return;
}
var entry = new DirectoryEntry("LDAP://blah.blah/DC=blah,DC=blah",
"cn=acct, dc=blah, dc=blah",
"pass");
var search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + userName + ")";
search.PropertiesToLoad.Add("memberOf");
var groupsList = new StringBuilder();
var result = search.FindOne();
if (result != null)
{
int groupCount = result.Properties["memberOf"].Count;
for (int counter = 0; counter < groupCount; counter++)
{
groupsList.Append((string)result.Properties["memberOf"][counter]);
groupsList.Append("\r\n");
}
}
txtResults.Text = groupsList.ToString();
When I run this code I get the following error on search.FindOne():
System.DirectoryServices.DirectoryServicesCOMException (0x8007203B): A local error has occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
at WebApplication1._Default.btnSearch_Click(Object sender, EventArgs e)
We've done a lot of research with this and twiddled every IIS7 setting we can think of, but no go so far. Any clues?
Change the username parameter from "cn=xxx, dc=yyy, dc=zzz" to "Domain\Username"
You can also change the IIS Application Pool to run a domain account with the query priveleges you are searching for.
I have a few other comments as well:
Make sure the first entry for the DirectoryEntry constructor includes the container for the users as well. This should help the DirectorySearcher to work more reliably.
I believe the second parameter in the DirectoryEntry constructor should be the user name, not the AD query path.
You should set the AuthenticationType property as well. With Server 2008, by default, this needs to be set to AuthenticationTypes.Secure | AuthenticationTypes.ServerBind | AuthenticationTypes.Sealing. I'd guess that 2008R2 has a simliar requirement.
I see that the question is rather old, but after struggling with this I thought to mention that it is indeed possible to use the LDAP-style of the username (in opposite to the DNS style). This works well for me:
string connString = "LDAP://MyDomain/CN=blah,DC=blah,DC=blah";
string username = "CN=MyAdmin,CN=Users,CN=blah,DC=blah,DC=blah";
string password = "myLittleSecret";
DirectoryEntry root = new DirectoryEntry(
connString,
username,
password,
AuthenticationTypes.None);
Where MyAdmin is a member in the Administrators role.
One little thing that took me a while to find is the AuthenticationTypes.None parameter that is needed if you do not want to communicate over SSL. Surely, you want to do this in production, but for development purposes it may be OK to skip the encryption.
Environment: Windows 7
I was also getting this exception when tried to query the active directory:
SearchResult result = srch.FindOne();
To resolve this, just put the above code inside Security.RunWithElevatedPrivileges().
Final Solution:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
result = srch.FindOne();
});