3

How can I check the user is exist or not in Active Directory. we are passing emailId as userName to the method parameter and it is GET method.

We have written this method, but it is not working properly.

[HttpGet("GetADUsers")]
public List<string> GetADUsers(string userName)
{
        var domainUsers = new List<string>();
        try
        {
            string domainName = _domainSettings.Value.DomainName;
            string domainUserName = _domainSettings.Value.UserName;
            string domainPassword = _domainSettings.Value.Password;

            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, domainUserName, domainPassword, ContextOptions.SimpleBind.ToString());

            UserPrincipal principalUser = new UserPrincipal(pc);

            using (var search = new PrincipalSearcher(principalUser))
            {
                foreach (var user in search.FindAll().Where(x => x.DisplayName == userName))
                {
                    if (user.DisplayName != null)
                    {
                        domainUsers.Add(user.DisplayName);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        return domainUsers;
    }
2
  • Your mistake is comparing the userName to the DisplayName. You should probably be comparing it to the SamAccountName property, which is the username in AD. But the answer by marc_s will likely be a faster search anyway. Commented Nov 26, 2018 at 13:43
  • Thanks, Gabriel Luci for your suggestion. Commented Nov 28, 2018 at 8:53

1 Answer 1

4

After you've created the PrincipalContext, you could just call UserPrincipal.FindByIdentity() - if the user is found, you get back the UserPrincipal - otherwise null.

[HttpGet("GetADUsers")]
public bool ADUserExists(string userName)
{
    string domainName = _domainSettings.Value.DomainName;
    string domainUserName = _domainSettings.Value.UserName;
    string domainPassword = _domainSettings.Value.Password;

    PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, domainUserName, domainPassword, ContextOptions.SimpleBind.ToString());

    UserPrincipal principalUser = UserPrincipal.FindByIdentity(pc, userName);

    if (principalUser != null) 
    {
         // gefunden ....            
         return true;
    }
    else
    {
         // nicht gefunden  
         return false;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You Buddy for the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.