I want to read data from an Active Directory within an ASP.NET Core 6 app. I know how this can be achieved with a DirectorySearcher:
var entry = new DirectoryEntry(GlobalConfig.Configuration.LDAP, Input.Username, Input.Password);
try
{
var _object = entry.NativeObject;
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = $"(SAMAccountName={Input.Username})";
searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("memberOf");
searcher.PropertiesToLoad.Add("employeeid");
searcher.PropertiesToLoad.Add("telephonenumber");
searcher.PropertiesToLoad.Add("displayName");
searcher.PropertiesToLoad.Add("mail");
SearchResult result = searcher.FindOne();
catch(Excepetion ex)
{
// ...
}
However, this solution does only work when we host the app within a windows environment. Is there any way to check this data with a cross plattform approach?
CodePudding user response:
You can use System.DirectoryServices.Protocols
package and specifically the LdapConnection
class.
Example:
using System.DirectoryServices.Protocols;
...
try
{
using var connection = new LdapConnection("{server}");
var networkCredential = new NetworkCredential(Input.Username, Input.Password, "{domain}");
connection.SessionOptions.SecureSocketLayer = false;
connection.AuthType = AuthType.Negotiate;
connection.Bind(networkCredential);
var searchRequest = new SearchRequest(
"{distinguishedName}",
$"(SAMAccountName={Input.Username})",
SearchScope.OneLevel,
new string[]
{
"cn",
"memberOf",
"employeeid",
"telephonenumber",
"displayName",
"mail"
});
SearchResponse directoryResponse = (SearchResponse)connection.SendRequest(searchRequest);
SearchResultEntry searchResultEntry = directoryResponse.Entries[0];
// ...
}
catch (LdapException ex)
{
// ...
}
Modify connection and search options accordingly. You can find documentation here. You might get warning for LdapSessionOptions.SecureSocketLayer
that it is only supported on Windows but this is a false warning that you can ignore.