任务是创建一个简单的WebAPI应用程序来测试与LDAP服务器的连接。我正在使用C#& .NET 4.5.1。 WebAPI应用程序位于我们的DMZ中(不在任何域中)。
我创建了一个简单的DirectorySearcher查找,但需要用户名和密码。
如果没有用户名和密码,该应用程序将如何检查对LDAP服务器的访问?
这是我的最新代码。我试图使用无效的用户名和密码登录。如果失败并显示“登录失败”消息,则表示我已与LDAP服务器建立连接。看起来像是一个黑客。想要一个更好的解决方案。
public Task<HttpResponseMessage> Ldap()
{
const string user = "0000";
const string pass = "0000";
const string messageTemplate = "{0} {1} {2} | LDAP: {3}";
HttpResponseMessage response;
var userName = String.Format("CN={0},OU=Users,DC=somelocation,DC=Org", user);
var path = "LDAP://ldap.somelocation.org/" + userName;
try
{
var directorySearcher = new DirectorySearcher
{
SearchRoot = new DirectoryEntry(path, userName, pass, AuthenticationTypes.ReadonlyServer),
SearchScope = SearchScope.Subtree
};
directorySearcher.PropertiesToLoad.AddRange(new[]
{
"givenName"
});
var entry = directorySearcher.FindOne().GetDirectoryEntry();
if (entry.Properties.Count > 0 && entry.Properties["givenName"].Value != null)
{
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(messageTemplate
.FormatWith(ApiFriendlyName, BuildLabel, BuildNumber,
entry.Properties["givenName"].Value))
};
}
else
{
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(messageTemplate
.FormatWith(ApiFriendlyName, BuildLabel, BuildNumber, "User not found."))
};
}
}
catch (Exception ex)
{
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(messageTemplate
.FormatWith(ApiFriendlyName, BuildLabel, BuildNumber,
ex.Message.Contains("Logon failure")
? "Connection made"
: "Connection failure"))
};
}
return Task.FromResult(response);
}