如何在asp.net?中从LDAP获取用户组

swvgeqrz  于 5个月前  发布在  .NET
关注(0)|答案(1)|浏览(83)

我有代码来验证用户从活动目录它的工作正常
但我需要检查用户组成员
我创建SearchRequest来查找用户组,但SearchResultEntry为空

LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier("my.server", 636));

    var networkCredential = new NetworkCredential("username", "password");
    ldapConnection.SessionOptions.SecureSocketLayer = true;
    ldapConnection.SessionOptions.ProtocolVersion = 3;
    ldapConnection.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(ServerCallback);
    ldapConnection.AuthType = AuthType.Negotiate;
    ldapConnection.Bind(networkCredential);

    SearchRequest Srchrequest = new SearchRequest("CN=username,DC=my.server", "OU=mygroup", System.DirectoryServices.Protocols.SearchScope.Subtree);
    SearchResponse SrchResponse = (SearchResponse)ldapConnection.SendRequest(Srchrequest);


    foreach (SearchResultEntry entry in SrchResponse.Entries)
    {
        entry.ToString();
        foreach (string attributename in entry.Attributes.AttributeNames)
        {
            ListBox2.Items.Add(attributename.ToString());
        }
    }

字符串

o0lyfsai

o0lyfsai1#

我用这段代码来获取用户组。希望对你有帮助。
appsettings.json:

"LDAPSettings": {
  "LdapServer": "your.server.com",
  "LdapUsername": "your-ldapuser",
  "LdapPassword": "your-password",
  "LdapBaseDN": "OU=Domain,OU=Users,DC=Domain,DC=com,DC=ar"
},

字符串
LDAP服务模型:

public class LDAPService
    {
        private readonly LDAPSettings _ldapSettings;
        private static readonly NLog.Logger Logger = NLog.LogManager.GetLogger("logfile");
    
        public LDAPService(IConfiguration configuration)
        {
            _ldapSettings = configuration.GetSection("LDAPSettings").Get<LDAPSettings>(); ;
        }
    
        public bool ValidateCredentials(string username, string password)
        {
            try
            {
                using (var connection = new LdapConnection())
            {
                int ldapPort = 389; // change this to your port

                connection.Connect(_ldapSettings.LdapServer, ldapPort);
                connection.Bind(_ldapSettings.LdapUsername, _ldapSettings.LdapPassword);

                // Make your authentication here
                // you can search and then verify credentials

                var searchFilter = $"(&(objectClass=user)(sAMAccountName={username}))";
                var searchResult = connection.Search(_ldapSettings.LdapBaseDN, 2, searchFilter, null, false);

                if (searchResult.HasMore())
                {
                    var userEntry = searchResult.Next();
                    var userDn = userEntry.Dn;

                    // Verify user's credentials
                    connection.Bind(userDn, password);

                    return connection.Bound;
                }
            }
        }
        catch (Exception ex)
        {
            Logger.Error(ex.Message + " || Funcion: ValidateCredentials()");
        }

        return false;
    }

    public async Task<List<string>> GetUserGroups(string username)
    {
        await Task.Delay(1);
        List<string> groups = new List<string>();
        groups.Add("primero para testear");
        try
        {
            using (var connection = new LdapConnection())
            {
                int ldapPort = 389;
                //Logger.Info($"{_ldapSettings.LdapServer} - {_ldapSettings.LdapBaseDN} - {_ldapSettings.LdapUsername} - {_ldapSettings.LdapPassword}");
                //Logger.Info("antes de conexion connect");
                connection.Connect(_ldapSettings.LdapServer, ldapPort);
                //Logger.Info("antes de conexion bind");
                connection.Bind(_ldapSettings.LdapUsername, _ldapSettings.LdapPassword);

                // get groups here
                string[] attrs = new string[] { "cn", "distinguishedName", "sAMAccountName", "userPrincipalName", "displayName", "givenName", "sn", "mail", "mailNickname", "memberOf", "homeDirectory", "msExchUserCulture" };
                
                var searchFilter = $"(userPrincipalName={username})";
                Logger.Info("Obtención de grupos " + searchFilter);
                var searchResult = connection.Search(_ldapSettings.LdapBaseDN, 2, searchFilter, null, false);
                // Logger.Info("pasa search result");
                //Logger.Info("seachResult count: " + searchResult.Count);
                //if(searchResult != null && searchResult.Count > 0)
                //{
                int cont = 0;
                string groupName;
                var nextEntry = searchResult.Next();
                var x = nextEntry.GetAttribute("memberOf").StringValueArray;
                List<string> lista = x.ToList();

                while (cont < lista.Count)
                {
                    //Logger.Info("seento a searc result ");
                    //Logger.Info("paso entry");
                    groupName = "nada";
                    if (lista[cont] == null) { groupName = "nulo"; }
                    else { groupName = lista[cont].ToString(); }
                    /*
                    if (nextEntry.GetAttribute("memberOf").StringValueArray[cont] == null) { groupName = "nulo"; }
                    else { groupName = nextEntry.GetAttribute("memberOf").StringValue; }
                    */
                    //Logger.Info("groupname: " + groupName);
                    groups.Add(groupName);
                    cont++;
                }
                //}
            }

        }
        catch (LdapException ex)
        {
            //Logger.Error(ex.Message + " || Funcion: GetUserGroups()");
        }

        return groups;
    }

}


LDAP设置模型

public class LDAPSettings
        {
            public string LdapServer { get; set; }
            public string LdapUsername { get; set; }
            public string LdapPassword { get; set; }
            public string LdapBaseDN { get; set; }
        }


注意:您需要从NuGet获得此软件包:Novell.Directory.Ldap. NET Standard
然后你应该在后端这样调用它:

List<string> listGroups= await _ldapService.GetUserGroups([email protected]); // this gives you a list of groups


希望它能帮助解决你的问题。

相关问题