使用C#对Active Directory进行身份验证

时间:2010-01-12 08:59:40

标签: c# authentication active-directory directoryservices

我只是拥有一个用户名而没有任何密码。我只想检查Active Directory中是否存在此用户名。我该怎么做呢?

3 个答案:

答案 0 :(得分:2)

如果您使用的是.NET 3.5,则可以使用System.DirectoryServices.AccountManagement功能。您的代码看起来像:

// create a "principal context" - e.g. your domain (could be machine, too)
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

UserPrincipal user = UserPrincipal.FindByIdentity(pc, "username");

bool userExists = (user != null);

应该这样做; - )

有关S.DS.AM的更多详细信息,请参阅这篇优秀的MSDN文章:

Managing Directory Security Principals in the .NET Framework 3.5

答案 1 :(得分:1)

试试这个:

string strDomain = DOMAINNAME;
string strUserId = USERNAME;

string strPath = "LDAP://DC=" + strDomain.Trim() + ",DC=com";

DirectoryEntry de = new DirectoryEntry(strPath);
DirectorySearcher deSearch = new DirectorySearcher(de);

deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + strUserId.Trim() + "))";

SearchResult results = deSearch.FindOne();
if ((results == null))
{
    //No User Found
}
else
{
   //User Found
}

答案 2 :(得分:0)

您可以使用班级DirectoryEntry执行此类任务。请在此处查看Exists - 方法:http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.exists.aspx