Check UserID exists in Active Directory using C#

情到浓时终转凉″ 提交于 2019-11-27 11:11:48

问题


How can we check whether the USERID exists in Active Directory or not.

I have LDAP String and UserID, can I find whether that UserID exists in Active Directory or not. I am using this for ASP.NET Web Application (.NET 3.5)


回答1:


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.

You can find more information at 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.




回答2:


I would use the System.DirectoryServices.AccountManagement namespace.

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



来源:https://stackoverflow.com/questions/4453801/check-userid-exists-in-active-directory-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!