【问题标题】:Check UserID exists in Active Directory using C#使用 C# 检查 Active Directory 中是否存在 UserID
【发布时间】:2011-05-26 02:59:53
【问题描述】:

我们如何检查 USERID 是否存在于 Active Directory 中。

我有 LDAP 字符串和用户 ID,我可以找到该用户 ID 是否存在于 Active Directory 中。我将它用于 ASP.NET Web 应用程序 (.NET 3.5)

【问题讨论】:

    标签: c# active-directory userid


    【解决方案1】:

    您可以按照以下方式进行操作(将域替换为您正在验证的域或完全删除参数):

    public bool DoesUserExist(string userName)
    {
        using (var domainContext = new PrincipalContext(ContextType.Domain, "DOMAIN"))
        {
            using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
            {
                return foundUser != null;
            }
        }
    }
    

    实现检查用户是否存在。这来自System.DirectoryServices.AccountManagement 命名空间和程序集。

    您可以在http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx找到更多信息

    您可能想进一步了解 PrincipalContext,因为它具有用于验证用户凭据等的有趣方法。

    【讨论】:

    • +1 我会做什么,只有更好的解释。此外,您可以省略域名称以使用本地域 - 如果您只有一个域并且不需要知道其名称,则很方便。
    • 感谢它的帮助.. 新的命名空间 System.DirectoryServices.AccountManagement 帮助..!!好吧,我对第二个参数“DOMAIN”有点迷信......?如果我们给它是 Active Directory 的域名,我们是否需要给它?...
    • 如果您想连接到系统的默认域,您可以删除该参数。否则,您需要指定要连接的域。
    • 如果您正在寻找答案,请不要忘记接受答案。 :)
    【解决方案2】:

    我会使用 System.DirectoryServices.AccountManagement 命名空间。

    string UserID = "grhm";
    bool userExists = false;
    
    using (var ctx = new PrincipalContext(ContextType.Domain))
    {
        using (var user = UserPrincipal.FindByIdentity(ctx, UserID))
        {
            if (user != null)
            {
                userExists = true;
                user.Dispose();
            }
        }
    }
    

    更多信息请见http://msdn.microsoft.com/en-us/library/bb344891.aspx

    【讨论】:

    • 谢谢它的工作,是的,新的命名空间。 System.DirectoryServices.AccountManagment 变得非常简单......
    • 我在一些示例中看到 PrincipleContext 有另一个参数“DOMAIN”...我们是否需要使用它?...
    • 您可以使用其他参数来指定您想要联系的域 - 就像在其他答案中一样。我看到 Joshua 在上面已经解释过了……
    • 你声明了user,但我从来没有看到usr 声明过。这些应该是同一个变量吗?
    • @BrianJ:是的,他们应该是。编辑修复它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 2019-04-06
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多