Home > Blockchain >  Connect to LDAP server and hit error in ASP.NET C# webform
Connect to LDAP server and hit error in ASP.NET C# webform

Time:06-15

I am using Windows authentication in a Webforms application, and I want to get the user's email address, but I think I hit the error when connecting to the server. Anything wrong with my code?

I had tried the strAccountId with/without domain name, (sAMAccountName=john).

The server is not operational.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: The server is not operational

Code:

string path = "LDAP://XYZ.LOCAL/CN=XYZ.LOCAL,OU=XXX,DC=XYZ,DC=LOCAL"; 
// The value of User.Identity.Name is XYZ\john
string strAccountId = "XYZ\\john";
string strPassword = "xxxxx";
bool bSucceeded;
string strError;

DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword);

DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);
adsSearcher.Filter = "(sAMAccountName="   strAccountId   ")";

try
{
    SearchResult adsSearchResult = adsSearcher.FindOne();
    bSucceeded = true;
    strError = "User has been authenticated by Active Directory.";
    EmailMsg.Text = strError;
    adsEntry.Close();
}
catch (Exception ex)
{
    bSucceeded = false;
    strError = ex.Message;
    EmailMsg.Text = strError;
    adsEntry.Close();
}

CodePudding user response:

In path you cannot put OUs, you need to do that after with adsEntry.Path.

string path = "LDAP://XYZ.LOCAL";
string strAccountId = "XYZ.LOCAL\\john";
string strPassword = "xxxxx";

DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword);
adsEntry.Path = "LDAP://CN=XYZ.LOCAL,OU=XXX,DC=XYZ,DC=LOCAL";
   

CodePudding user response:

Your path has three parts:

  1. LDAP:// is the protocol
  2. XYZ.LOCAL is the server to connect to. This is optional and can be excluded if the computer you run this from is joined to the same domain you're trying to connect to, or to a trusted domain.
  3. CN=XYZ.LOCAL,OU=XXX,DC=XYZ,DC=LOCAL is the object on the domain to bind to. This is also optional. If excluded, it will bind to the root of the domain that the server in part 2 is part of. You must include either part 2 or 3, or both.

Since you have included the optional server name, it will try to connect to XYZ.LOCAL on the default LDAP port 389. "The server is not operational" means that it could not open a connection to XYZ.LOCAL on port 389. This is a network error and you need to figure out why the domain is not accessible from the computer you are running this from.

You can test the connection in PowerShell using:

Test-NetConnection XYZ.LOCAL -Port 389
  • Related