简体   繁体   English

使用C#检查Active Directory中是否存在UserID

[英]Check UserID exists in Active Directory using C#

How can we check whether the USERID exists in Active Directory or not. 我们如何检查USERID中是否存在USERID。

I have LDAP String and UserID, can I find whether that UserID exists in Active Directory or not. 我有LDAP String和UserID,我可以找到Active Directory中是否存在该UserID。 I am using this for ASP.NET Web Application (.NET 3.5) 我在ASP.NET Web应用程序(.NET 3.5)中使用它

You can do something along the lines of (replacing domain with the domain you're authenticating against or removing the parameter altogether): 您可以执行某些操作(使用您要进行身份验证的域替换域或完全删除参数):

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;
        }
    }
}

To achieve checking for if a user exists. 实现检查用户是否存在。 This comes from the System.DirectoryServices.AccountManagement namespace and assembly. 它来自System.DirectoryServices.AccountManagement命名空间和程序集。

You can find more information at http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx 您可以在http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx上找到更多信息。

You may want to check more into PrincipalContext as it has interesting methods for authenticating user credentials and such. 您可能希望更多地检查PrincipalContext,因为它有用于验证用户凭据等的有趣方法。

I would use the System.DirectoryServices.AccountManagement namespace. 我会使用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();
        }
    }
}

See http://msdn.microsoft.com/en-us/library/bb344891.aspx for more info 有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/bb344891.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM