I'm trying to get LDAP authentication working using the .NET System.DirectoryServices.Protocol namespace. (This is necessary as I simply cannot get my existing code using System.DirectoryServices to communicate with our client's LDAP server.)
I've managed to get everything working, with the exception that when I try and return the userAccountControl attribute for the user account, it is returning a string representation of the value, when it should be returning an integer. (The value in the Active Directory is definitely an integer.)
In the following code, if I breakpoint at userAccountFlags = (int)attrib[0]; the type of attrib[0] is a string. Why?
(I can easily "fix" it by replacing it with int.TryParse((string)attrib[0], out userAccountFlag); but would prefer to know why it's happening than use this work-around.)
var ident = new LdapDirectoryIdentifier(domain, (ssl ? 636 : 389));
using (var conn = new LdapConnection(ident))
{
conn.Credential = new NetworkCredential(domainUsername, domainPassword);
conn.AuthType = AuthType.Basic;
if (ssl)
{
conn.SessionOptions.SecureSocketLayer = true;
conn.SessionOptions.VerifyServerCertificate = (connection, certificate) => true;
}
conn.Bind();
var request = new proto.SearchRequest(rootDN, testDN, SearchScope.Subtree);
request.Attributes.Add("userAccountControl");
request.SizeLimit = 1;
var response = (SearchResponse)conn.SendRequest(request);
if (response.Entries.Count != 0)
{
int userAccountFlags = int.MinValue;
foreach (proto.SearchResultEntry entry in response.Entries)
{
foreach (proto.DirectoryAttribute attrib in entry.Attributes.Values)
{
if (attrib.Name == "userAccountControl" && attrib.Count > 0)
{
// The following line breaks, as "attrib[0] is string = true"
userAccountFlags = (int)attrib[0];
break;
}
}
}
}
}
The values returned from the attribute will always be either a string or byte array.
From the documentation of the DirectoryAttribute indexer:
The Get method of Item always attempts to convert and return the value object as a string; otherwise it returns a byte array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With