How to check if a user exists on LDAP

五迷三道 提交于 2019-12-21 05:04:18

问题


I need to verify users in the company using only their username - not their password.

So I need a method like this

public bool UserExists(string username)
{ ... }

I am aware of the System.DirectoryServices namespace but don't know where to start.

Any ideas?

There are 80,000+ records so try to bear that in mind.

Thank you.

Edit:

I have done it - my code is:

private bool UserExists(string userName, string domain)
{
    try
    {
        DirectoryEntry.Exists("WinNT://" + domain + ".[hidden].com/" + userName);
        return true;
    }
    catch (COMException)
    {
        return false;
    }
}

I don't know if it is correct, but it seems to work so far.

Michael's answer has two relevant parts:

  • http://www.codeproject.com/KB/system/everythingInAD.aspx#22
  • http://www.codeproject.com/KB/system/everythingInAD.aspx#35

Update #2:

I actually used this:

public static bool LoggedOnUserExists()
{
    var domain = new PrincipalContext(ContextType.Domain);

    UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, Environment.UserName);

    return foundUser != null;
}

回答1:


In .NET 3.5 and up, you can use the System.DirectoryServices.AccountManagement namespaces to do this quite simply:

public bool UserExists(string username)
{
   // create your domain context
   using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
   {
       // find the user
       UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);

       return foundUser != null;
    }
}

This will work with the regular user name John Doe, or alternatively you can use the user's e-mail address (john.doe@company.com), or his distinguished name (CN=John Doe) - see what the IdentityType enumeration has to offer :-)




回答2:


Good article to start:

Howto: (Almost) Everything In Active Directory via C#



来源:https://stackoverflow.com/questions/4304565/how-to-check-if-a-user-exists-on-ldap

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