You should try breaking this into separate parts, so it's easier to manage the logic, and easier to locate where your errors are occurring. I usually go with the following approach in this situation :
- Create an
LdapConnection
object so you can set the options you need
- Setup a
NetworkCredential
instance with an administrative username and password
- Bind to the directory with the user so you can issue a direct LDAP query
- Return a
SearchResultEntry
so you can process the properties
You have a few options to help you accomplish this, but I'd try something like this :
//Delcare your Network Credential with the administrative Username, Password, and your active directory domain
var credentials = new NetworkCredential(userName, password, domain);
//Create a directory identifier and connection,
var ldapidentifier = new LdapDirectoryIdentifier(serverName, port, false, false);
var ldapconn = new LdapConnection(ldapidentifier, credentials);
Next, make sure you're setting the right AuthType
for your particular instance. Since you're connecting over port 389, just use AuthType.Basic
.
ldapconn.AuthType = AuthType.Basic;
As you had asked, there is a very easy way to setup a direct LDAP query using this approach. I'm assuming you're searching by sAMAccountName
, but you can modify this as needed :
string ldapFilter = "(&(objectCategory=person)(objectClass=user)(&(sAMAccountName={{UserYouAreTryingToFind}})))";
Now we just have to setup the search request, and send it accordingly :
//Send the search request with our delimited attribute list
var getUserRequest = new SearchRequest(domain, ldapFilter, SearchScope.Subtree, AttributeList)
{SizeLimit = 1};
//Suppress any refferal creation from happening during the search
var SearchControl = new SearchOptionsControl(SearchOption.DomainScope);
getUserRequest.Controls.Add(SearchControl);
var userResponse = (SearchResponse)ldapconn.SendRequest(getUserRequest);
//This is where I load up the entry I've located,
SearchResultEntry ResultEntry = userResponse.Entries[0];
That should return the user you've queried for, along with any properties you've put into AttributeList
. In this context, AttributeList
is just a string array (string[]
) of property names - in your case you'll want to add one called "objectGUID".
As for reading the properties on the SearchResultEntry
, you can do exactly what you had originally :
if(ResultEntry.Attributes.Contains("objectGUID"))
{
// do some stuff here
}
That should help get you going in the right direction.
Also, if you don't already have a copy of wireshark, I highly suggest you download it - it will be invaluable in diagnosing connection issues with active directory.