创建一个与Active Directory通信的Web服务,以验证用户并确定他们属于哪些组。
我从验证过程开始,并且正常运行:
public bool AuthenticateAdUser(string username, string password)
{
//in the real code, these come from config
string domain = "TestDomain";
string server = 666.666.666.666;
string authType = "Basic";
string useSsl = "false";
AuthType atype = (AuthType)Enum.Parse(typeof(AuthType), authType);
using (var ldapConnection = new LdapConnection(server))
{
var networkCredential = new NetworkCredential(username, password, domain);
ldapConnection.SessionOptions.SecureSocketLayer = Convert.ToBoolean(useSsl);
ldapConnection.AutoBind = false;
ldapConnection.AuthType = atype;
ldapConnection.Bind(networkCredential);
}
// If the bind succeeds, the credentials are valid
return true;
}
但是,我不清楚如何使用LdapConnection对象来处理组。文档和示例建议您使用PrinicpalContext来实现此目的。所以我尝试了这个。
string domain = "TestDomain";
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
{
using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, username).GetGroups(pc))
{
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
}
}
此操作失败,声称无法联系Active Directory服务器。使用DNS样式名称(“TestDomain.local”)似乎没有帮助。
这至少会启动网络主体:
string server = "666.666.666.666";
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, server))
{
using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, username).GetGroups(pc))
{
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
}
}
但是当您尝试对其执行任何操作时,它会因“未找到网络路径”而失败。
有关Principal无法工作的原因,或者我如何使用LdapConnection查询组?