简体   繁体   English

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

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

I'm trying to search active directory by the username 'admin'. 我正在尝试使用用户名“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. userResult总是以null结尾。 I would love to know why, there must be something that I'm missing. 我很想知道为什么,必须有一些我不知道的东西。

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. 如果您使用的是.NET 3.5及更高版本,则应该查看System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。 Read all about it here: 在这里阅读所有相关内容:

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). DistinguishedName :标识是专有名称(DN)。
  • Guid : The identity is a Globally Unique Identifier (GUID). Guid :身份是全球唯一标识符(GUID)。
  • Name : The identity is a name. Name :身份是一个名称。
  • SamAccountName : The identity is a Security Account Manager (SAM) name. SamAccountName :标识是安全帐户管理器(SAM)名称。
  • Sid : The identity is a Security Identifier (SID) in Security Descriptor Definition Language (SDDL) format. Sid :标识是安全描述符定义语言(SDDL)格式的安全标识符(SID)。
  • UserPrincipalName : The identity is a User Principal Name (UPN). UserPrincipalName :标识是用户主体名称(UPN)。

The new S.DS.AM makes it really easy to play around with users and groups in AD! 新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!

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

if you want to stick to DirectorySearcher, try searching by cn or samaccountname instead 如果您想坚持使用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();

It turns out that "userPrincipalName" needed to be all lower-case ("userprincipalname"). 事实证明,“userPrincipalName”必须全部为小写(“userprincipalname”)。 Good to know, thanks for your responses. 很高兴知道,感谢您的回复。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从C#中的显示名称获取Active Directory中的用户名? - How to get a username in Active Directory from a display name in C#? 如何从使用C#的用户名获取存储在Active Directory中的真实姓名? - How do I get a real name stored in Active Directory from an username with C#? 如何在C#中使用用户名和密码在活动目录中找到用户及其所属的安全组? - How do I find a user and the security group they belong to in active directory with their username and password in C#? 如何使用C#在Active Directory用户路径中使用%username%变量? - How to use %username% variable in Active Directory user paths using C#? 如何在c#中查询Active Directory站点和服务? - How can I query Active Directory Sites and Services in c#? C# 活动目录搜索 - C# Active Directory Search 如何使用 c# 以编程方式创建本地 Active Directory? - How can I create a local Active Directory programatically using c#? 如何使用C#更好地查询Active Directory中的多个域? - How can I better query multiple domains in Active Directory using C#? 如何使用C#检查用户是否在Active Directory中具有写权限? - How can I check if a user has write rights in Active Directory using C#? 如何使用C#在Active Directory中检索schemaNamingMaster? - How do I retrieve the schemaNamingMaster in Active Directory using C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM