我一直在网上搜索Active Directory和Windows身份验证。我成功从域AD获取用户信息但我必须传递用户名和密码。所以,让你进入我的背景:
我有一个我设置用户的域名。每个用户将使用其给定的凭据连接到域。因此,他们将登录到他们的PC,当他们打开一个VS 2013 C#应用程序时,它将检查用户是否存在于域上,如果用户那么返回AD信息,如果用户不存在则显示登录页面进入证书。因为我可以让外部用户连接到我的域等...
现在我无法使用用户的Windows身份验证访问AD,它在Search.FindOne();
public static void GetActiveDirectoryUser(string UserName)
{
try
{
// Create LDAP connetion object
DirectoryEntry ldapConnection = CreateDirectoryEntry();
// Create Search object which operates on LDAP connection object
// and set search object to only find the user specified
DirectorySearcher search = new DirectorySearcher(ldapConnection);
// Create results objects from search object
SearchResult result = search.FindOne();
if (result != null)
{
// User exists, cycle through LDAP fields (cn, telephonenumber, etc.)
ResultPropertyCollection fields = result.Properties;
foreach (string ldapField in fields.PropertyNames)
{
// Cycle through objects in each field e.g group membership
foreach (Object objCollection in fields[ldapField])
{
Console.WriteLine(String.Format("{0, -20} : {1}", ldapField, objCollection.ToString()));
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception Caught:\n\n" + e.ToString());
}
}
static DirectoryEntry CreateDirectoryEntry()
{
string pathDomainName = "WinNT://MyDomain/Fred,Person";
DirectoryEntry ldapConnection = new DirectoryEntry(pathDomainName);
return ldapConnection;
}
这是我遇到的错误
System.Runtime.InteropServices.COMException (0x80005000): Unknown error (0x80005000)
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
但是当我使用这个字符串时
string pathDomainName = "LDAP://MyDomain";
DirectoryEntry directoryEntry = new DirectoryEntry(pathDomainName, "Fred", "f12345!");
它可以工作,它为用户返回了我的所有AD,但是我已经使用Windows身份验证登录了,为什么我会再次传递凭据?我只需要知道,如果用户存在于域
上由于
答案 0 :(得分:2)
如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有相关内容:
基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
}
// or alternatively: get the currently logged in user
UserPrincipal current = UserPrincipal.Current;
.....
}
新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!