How to check if a user exists in LDAP

I need to check users in the company using only their username and not password.

So I need a method like this

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

I know the System.DirectoryServices namespace, but I don’t know where to start.

Any ideas?

There are 80,000+ entries, so try not to forget about it.

Thanks.

Edit:

I did this - my code:

 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 this is correct, but it seems to be working so far.

Michael answers in two important parts:

Update # 2:

I really used this:

 public static bool LoggedOnUserExists() { var domain = new PrincipalContext(ContextType.Domain); UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, Environment.UserName); return foundUser != null; } 
+5
source share
2 answers

In .NET 3.5 and later, you can use the System.DirectoryServices.AccountManagement namespaces to make this pretty simple:

 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 usual John Doe username or, alternatively, you can use the user's email address ( john.doe@company.com ) or his distinguished name ( CN=John Doe ) - see what the IdentityType enumeration has to offer IdentityType

+5
source

Source: https://habr.com/ru/post/898681/


All Articles