是否有一个.NET类可以解析LDAP中的CN =字符串?

Gab*_*own 12 .net ldap active-directory

我有一个字符串,我从LDAP获取Active Directory组成员资格,我需要解析它以检查用户是否是AD组的成员.有没有可以解析这个问题的课程?

例:

CN=Foo Group Name,DC=mydomain,DC=com
Run Code Online (Sandbox Code Playgroud)

mar*_*rkt 7

如果您不想添加其他依赖项,只想解析字符串..

只需使用string.Split就可以轻松解析这种类型的字符串.要获得CN值,将会是......

string[] split = "CN=Foo Group Name,DC=mydomain,DC=com".Split(',');
List<string> cnValues = new List<string>();
foreach(string pair in split){
    string[] keyValue=pair.Split('=');
    if(keyValue[0]=="CN")
       cnValues.Add(keyValue[1]);
}
Run Code Online (Sandbox Code Playgroud)

  • 对于那些回读的人来说,这个解决方案对于生产环境是不够的 - [RFC](http://www.rfc-archive.org/getrfc.php?rfc=4514)指定可以引用值并在那里也是角色逃避规则.此外,用这种格式用逗号分割字符串是非常危险的. (25认同)

spo*_*son 6

这些被称为专有名称.

CodeProject有一个解析器项目,可以满足您的需求:http://www.codeproject.com/KB/IP/dnparser.aspx


Wil*_*ler 5

此外,如果您查询组成员的AD,您将能够直接比较所有成员的distinguishedName,而无需通过命名空间的DirectoryEntry类来解析代码System.DirectoryServices

否则,我只是不知道某处有这样的课程。=)

希望无论如何这会有所帮助!

编辑#1

这是一个链接,我从中学到了很多关于 AD 和System.DirectoryServices命名空间的知识:Howto: (Almost) Everything In Active Directory via C#

我将在几天后为您提供示例代码,如果您仍然需要它,我将使用System.DirectoryServices.DirectorySearcher对象类来检索组的成员。

我希望这个链接能像对我一样帮助你!=)

编辑#2

这是我告诉过你的代码示例。这应该可以更有效地查询 AD,而无需来回处理 AD。

public IList<string> GetMembers(string groupName) {
    if (string.IsNullOrEmpty(groupName))
        throw new ArgumentNullException("groupName");

    IList<string> members = new List<string>();

    DirectoryEntry root = new DirectoryEntry(@"LDAP://my.domain.com");
    DirectorySearcher searcher = new DirectorySearcher();
    searcher.SearchRoot = root;
    searcher.SearchScope = SearchScope.Subtree;
    searcher.PropertiesToLoad.Add("member");

    searcher.Filter = string.Format("(&(objectClass=group)(sAMAccountName={0}))", groupName);

    SearchResult result = searcher.FindOne();
    DirectoryEntry groupFound = result.GetDirectoryEntry();
    for (int index = 0; index < ((object[])groupFound.Properties["member"].Value).Length; ++index)
        members.Add((string)((object[])groupFound.Properties["member"].Value)[index]);

    return members;

}
Run Code Online (Sandbox Code Playgroud)

免责声明此代码按原样提供。我在我的本地机器上测试了它,它工作得很好。但是因为我不得不在这里重新输入它,因为我不能只是复制粘贴它,所以我在输入时可能犯了一些错误,我希望没有发生。