How can I search Active Directory by username using C#?

你。 提交于 2020-01-01 11:01:13

问题


I'm trying to search active directory by the username 'admin'. I know for a fact that there is a user with that username in the directory, but the search keeps coming back with nothing.

var attributeName = "userPrincipalName";
var searchString = "admin"
var ent = new DirectoryEntry("LDAP://"dc=corp,dc=contoso,dc=com")
var mySearcher = new DirectorySearcher(ent);
mySearcher.Filter = string.Format("(&(objectClass=user)({0}={1}))", attributeName, searchString);

var userResult = mySearcher.FindOne();

userResult always ends up null. I would love to know why, there must be something that I'm missing.


回答1:


If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "admin");

if(user != null)
{
   // do something here....     
}

With this code, you'll be searching for that user by the following attributes:

  • DistinguishedName : The identity is a Distinguished Name (DN).
  • Guid: The identity is a Globally Unique Identifier (GUID).
  • Name: The identity is a name.
  • SamAccountName: The identity is a Security Account Manager (SAM) name.
  • Sid: The identity is a Security Identifier (SID) in Security Descriptor Definition Language (SDDL) format.
  • UserPrincipalName: The identity is a User Principal Name (UPN).

The new S.DS.AM makes it really easy to play around with users and groups in AD!




回答2:


this should work

private void showUsers(string pUserName)
    {
        string uid = Properties.Settings.Default.uid;
        string pwd = Properties.Settings.Default.pwd;
        using (var context = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", uid, pwd))
        {
            using (UserPrincipal user = new UserPrincipal(context))
            {
                user.SamAccountName = pUserName;
                using (var searcher = new PrincipalSearcher(user))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                        Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
                        Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
                        Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
                        Console.WriteLine("Mail: " + de.Properties["mail"].Value);

                        PrincipalSearchResult<Principal> groups = result.GetGroups();

                        foreach (Principal item in groups)
                        {
                            Console.WriteLine("Groups: {0}: {1}", item.DisplayName, item.Name);
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
        Console.WriteLine("End");
        Console.ReadLine();
    }



回答3:


if you want to stick to DirectorySearcher, try searching by cn or samaccountname instead

var attributeName = "cn";
var searchString = "admin"
var ent = new DirectoryEntry("LDAP://"dc=corp,dc=contoso,dc=com")
var mySearcher = new DirectorySearcher(ent);
mySearcher.Filter = string.Format("(&(objectcategory=user)({0}={1}))", attributeName, searchString);

var userResult = mySearcher.FindOne();



回答4:


It turns out that "userPrincipalName" needed to be all lower-case ("userprincipalname"). Good to know, thanks for your responses.




回答5:


var attributeName = "userPrincipalName";
var = "admin"

You need change filter like this

string filter="(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(attributeName =searchString))";



var ent = new DirectoryEntry("LDAP://"dc=corp,dc=contoso,dc=com")
var mySearcher = new DirectorySearcher(ent);
mySearcher.Filter = filter;

var userResult = mySearcher.FindOne();


来源:https://stackoverflow.com/questions/16865154/how-can-i-search-active-directory-by-username-using-c

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