如何在C#Core 2中使用LDAP查找用户组 [英] How to find a User's Group with LDAP in C# Core 2

查看:63
本文介绍了如何在C#Core 2中使用LDAP查找用户组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Active Directory作为身份验证方法的C#Core 2,并带有 Novell -我已经使基于密码的验证用户"部分起作用,如果AD中的用户名和密码正确,则对他们进行身份验证.

I am using C# Core 2 using Active Directory as the authentication method with Novell - I have got the verify user based on password section working, authenticating them if the username and password are correct in AD.

我想以相同的方式获取登录用户的用户组,以进一步提高安全性.

I want to get the user group of the logged in user, to add further security, in the same way [Authorize(roles="*")]would.

下面的代码是我到目前为止所拥有的,我知道连接正确,但是我无法在SearchResults中得到任何结果,它总是以0计数返回.

The below code is what I have so far, I know the connection is correct, but I cannot get any results in the SearchResults, it always returns as a count of 0.

我要去哪里错了?以前没有任何Active Directory暴露.

Where am I going wrong? Not had any previous Active Directory exposure.

搜索功能:

    int searchScope = LdapConnection.SCOPE_BASE;
    string searchFilter = "(CN = " + username + ")";
    string searchBase = "OU=Users,OU=TOD,OU=Departments,DC=domain,DC=com";
    // folder structure Users/TOD/Departments/List of people

    // reading members of dynamic group could take long so set timeout to 10 seconds
    LdapSearchConstraints constraints = new LdapSearchConstraints();
    constraints.TimeLimit = 10000;

    #region connection
    string host = "mydomain.com";
    string un = "mydomain\\" + username;
    int port = 389;
    int version = LdapConnection.Ldap_V3;

    var conn = new LdapConnection();

    conn.SecureSocketLayer = false;
    conn.Connect(host, port);
    conn.Bind(version, un, pass); //parsed in through function params
    #endregion

    LdapSearchResults searchResults = conn.Search(
        searchBase,
        searchScope,
        searchFilter,
        null, // no specified attributes
        false, // return attr and value
        constraints);
      // always returns a search with 0 count

已更新:

我间歇性地收到LDAP连接错误,在其他情况下,搜索返回为空-我不知道这是否与等待有关,但它将立即达到我在 conn处设置的断点.Disconnect(),而不是while循环中的任何断点.

I am getting LDAP connection errors intermittently, and on other occasions the search is brought back as empty - I don't know if this is to do with waiting but it will immediately hit the break point I set at conn.Disconnect() rather than any break points in the while loop.

[TestMethod]
    public void SearchForUserDepartentTest()
    {
        var users = new Dictionary<string,string>();
        var count = 0;

        string searchFilter = "(objectclass=*)";
        string searchBase = "OU=Departments,DC=domain,DC=com"; //ou=users, ou=TOD

        // reading members of dynamic group could take long so set timeout to 10 seconds
        LdapSearchConstraints constraints = new LdapSearchConstraints();
        constraints.TimeLimit = 10000;

        #region connection
        string host = "domain.com";
        string un = "domain\\doatemp2";
        string pass = "****";
        int port = 389;
        int version = LdapConnection.Ldap_V3;

        var conn = new LdapConnection
        {
            SecureSocketLayer = false
        };
        conn.Connect(host, port);
        conn.Bind(version, un, pass);
        #endregion
        try
        {
            LdapSearchResults searchResults = conn.Search(
                searchBase,
                LdapConnection.SCOPE_ONE,
                searchFilter,
                null, // no specified attributes
                false, // return attr and value
                constraints);

            while (searchResults.hasMore())
            {
            // doesn't hit in here intermittently
                count++;
                var nextEntry = searchResults.next();

                nextEntry.getAttributeSet();
                var attr = nextEntry.getAttribute("NAME");

                if (attr == null)
                {
                    users.Add("Distinguished Name", nextEntry.getAttribute("distinguishedName").StringValue);
                }
                else
                {
                    users.Add((nextEntry.getAttribute("SAMACCOUNTNAME") == null)? "NULL ACC Name " + count : nextEntry.getAttribute("SAMACCOUNTNAME").StringValue
                        ,(nextEntry.getAttribute("DISTINGUISHEDNAME") == null)? "NULL DN" + count : nextEntry.getAttribute("distinguishedName").StringValue);
                }                    
            }
        }
        catch (LdapException ldapEx)
        {
            ldapEx.ToString(); // ocassional time outs
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
        conn.Disconnect(); // when run hits the break point here, missing out the anything in searchResults.hasMore()
    }

更新2:

最新代码.

[TestMethod]
public void SearchForUserDepartentTest()
{ 
    var users = new Dictionary<string,string>();
    var count = 0;

    string searchFilter = "(objectclass=*)";
    string searchBase = "OU=Departments,DC=domain,DC=com"; //ou=users, ou=TOD

    // reading members of dynamic group could take long so set timeout to 10 seconds
    LdapSearchConstraints constraints = new LdapSearchConstraints();
    constraints.TimeLimit = 30000;

    #region connection information
    string host = "domain";
    string un = "domain\\doatemp2";
    string pass = "";
    int port = 389;
    int version = LdapConnection.Ldap_V3;
    #endregion

    try
    {
        using (var conn = new LdapConnection { SecureSocketLayer = false })
        {
            conn.Connect(host, port);
            conn.Bind(version, un, pass);

            LdapSearchResults searchResults = conn.Search(
                searchBase,
                LdapConnection.SCOPE_SUB,
                searchFilter,
                null, // no specified attributes
                false, // return attr and value
                constraints);

            while (searchResults.hasMore())
            {
                count++;
                var nextEntry = searchResults.next();

                nextEntry.getAttributeSet();
                var attr = nextEntry.getAttribute("NAME");

                if (attr == null)
                {
                    users.Add("Distinguished Name", nextEntry.getAttribute("distinguishedName").StringValue);
                }
                else
                {
                    users.Add((nextEntry.getAttribute("SAMACCOUNTNAME") == null) ? "NULL ACC Name " + count : nextEntry.getAttribute("SAMACCOUNTNAME").StringValue, 
                        (nextEntry.getAttribute("DISTINGUISHEDNAME") == null) ? "NULL DN" + count : nextEntry.getAttribute("distinguishedName").StringValue);
                }
            }
        }
    }
    catch (LdapException ldapEx)
    {
        ldapEx.ToString(); // ocassional time outs
    }
    catch (Exception ex)
    {
        ex.ToString();
    }

    var check = users;
}

更新3:在案例测试环境中使用Core控制台应用程序会造成不利影响.通过下面的代码,可以读取LdapConnection超时85

UPDATE 3: Using Core console application in case testing environment was causing adverse effects. With below code getting a readout of LdapConnection timeout 85

公共静态无效SearchForUserDepartent(){var users = new Dictionary();var count = 0;

public static void SearchForUserDepartent() { var users = new Dictionary(); var count = 0;

string searchFilter = "(objectclass=*)";//string.Empty;
string searchBase = "OU=Users,OU=TOD,OU=Departments,DC=domain,DC=com";

LdapSearchConstraints constraints = new LdapSearchConstraints
{
    TimeLimit = 15000
};

#region connection information
string host = "dm1.domain.com";
string un = "domain\\doatemp2";
string pass = "password";
int port = 389;
#endregion

try
{
    using (var conn = new LdapConnection { SecureSocketLayer = false })
    {
        conn.Connect(host, port);
        conn.Bind(un, pass);

        LdapSearchResults searchResults = conn.Search(
            searchBase,
            LdapConnection.SCOPE_SUB,
            searchFilter,
            null, // no specified attributes
            false, // return attr and value
            constraints);

        while (searchResults.hasMore())
        {
            count++;
            var nextEntry = searchResults.next(); // hits and then goes to timeout

            nextEntry.getAttributeSet();
            Console.WriteLine("Distinguished Name:" + nextEntry.getAttribute("distinguishedName").StringValue);
            Console.ReadKey();
        }
    }
}
catch (LdapException ldapEx)
{
    Console.WriteLine(ldapEx.ToString()); // ocassional time outs
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}
    foreach(var u in users)
    {
        Console.WriteLine("Key:" + u.Key.ToString() + " | Value:" + u.Value.ToString());
    }
Console.ReadKey();
}

推荐答案

LdapSearchResults计数始终为0,则应使用.hasMore()获取搜索值

LdapSearchResults Count always 0, you should use .hasMore() to get value of your searching

尝试这样的想法

                var users = new HashSet<string>();
//My domain have 4 DC's
            LdapSearchResults searchResults = conn.Search(
                "CN=Users,DC=z,DC=x,DC=c,DC=v",//You can use String.Empty for all domain search. This is example about users
                LdapConnection.SCOPE_SUB,//Use SUB
                "(mail=*@somemail.com)",// Example of filtering with *. You can use String.Empty to query without filtering
                null, // no specified attributes
                false // return attr and value
                );

            while (searchResults.hasMore())
            {
                var nextEntry = searchResults.next();
                nextEntry.getAttributeSet();
                var attr = nextEntry.getAttribute("mail");

                if (attr == null)
                {
                    users.Add(nextEntry.getAttribute("distinguishedName").StringValue);
                }
                else {
                    users.Add(nextEntry.getAttribute("mail").StringValue);
                }

            }

为获得更好的查询,请使用ActiveDirectory用户和计算机.有属性编辑器可以提供有关DC,CN,OU和attrs的所有信息.

for better querying use ActiveDirectory Users and computers. there are has attribute editor witch can provide all information about DC,CN,OU and attrs

有关更多信息,请访问此处

Also more info at here and here

更新:作为官方文档说:

SCOPE_BASE:与搜索一起使用以指定条目范围搜索是仅搜索基本对象.

SCOPE_BASE:Used with search to specify that the scope of entrys to search is to search only the base obect.

SCOPE_ONE:与搜索一起使用,以指定要输入的条目的范围搜索是仅搜索基本对象的直接下属.

SCOPE_ONE:Used with search to specify that the scope of entrys to search is to search only the immediate subordinates of the base obect.

SCOPE_SUB:与搜索一起使用以指定条目范围搜索是搜索基础对象及其内部的所有条目子树.

SCOPE_SUB:Used with search to specify that the scope of entrys to search is to search the base object and all entries within its subtree.

SCOPE_SUB意味着您可以在没有完整输入路径的情况下使用searchBase或使用string.Empty进行完整域搜索

SCOPE_SUB that means that you can use searchBase without full entry path or use string.Empty to full domain search

这篇关于如何在C#Core 2中使用LDAP查找用户组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆