【问题标题】:Authentication against Active Directory using C#使用 C# 针对 Active Directory 进行身份验证
【发布时间】:2010-01-12 08:59:39
【问题描述】:

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

【问题讨论】:

  • 您应该始终将语言添加到标签列表中;)

标签: c# authentication active-directory directoryservices


【解决方案1】:

如果您使用的是 .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

【讨论】:

    【解决方案2】:

    试试这个:

    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
    }
    

    【讨论】:

    • 我建议使用 objectCategory=person 而不是 objectClass。 ObjectCategory 是单值和索引的,而 objectClass 不是 --> 使用 objectCategory 可以让您的 AD 查询更快
    • @marc_s:可以同时使用 objectCategoryobjectClassobjectClass 仅作为使用 objectCategory 仅在过滤器中在 .NET 中不起作用。
    • 您不应使用此方法,因为它还会尝试读取 Active Directory 中的值,而不是检查身份验证。您可以拥有有效的凭据,但代码将失败,因为您无权查找用户。
    【解决方案3】:

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

    【讨论】: