如何使用 C# 按用户名搜索 Active Directory?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16865154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:59:40  来源:igfitidea点击:

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

c#active-directory

提问by speedreeder

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.

我正在尝试通过用户名“admin”搜索活动目录。我知道目录中有一个具有该用户名的用户,但搜索一直没有返回。

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.

userResult 总是以 null 结束。我很想知道为什么,一定有我遗漏的东西。

采纳答案by speedreeder

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

事实证明,“userPrincipalName”需要全部小写(“userprincipalname”)。很高兴知道,感谢您的回复。

回答by marc_s

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:

如果您使用 .NET 3.5 及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM) 命名空间。在这里阅读所有相关信息:

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

基本上,您可以定义域上下文并轻松找到 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).
  • DistinguishedName: 标识是一个专有名称 (DN)。
  • Guid:标识是一个全局唯一标识符 (GUID)。
  • Name: 身份是一个名字。
  • SamAccountName:标识是安全帐户管理器 (SAM) 名称。
  • Sid:身份是安全描述符定义语言 (SDDL) 格式的安全标识符 (SID)。
  • UserPrincipalName:标识是用户主体名称 (UPN)。

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

新的 S.DS.AM 使在 AD 中与用户和组一起玩变得非常容易!

回答by Jason

if you want to stick to DirectorySearcher, try searching by cnor samaccountnameinstead

如果您想坚持使用 DirectorySearcher,请尝试通过cnsamaccountname代替

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();

回答by kombsh

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();

回答by Ivanzinho

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();
    }