Skip to content

Instantly share code, notes, and snippets.

@mihaimyh
Created February 18, 2022 20:57
Show Gist options
  • Save mihaimyh/3053fc528603a2ad4aab3c253d56178a to your computer and use it in GitHub Desktop.
Save mihaimyh/3053fc528603a2ad4aab3c253d56178a to your computer and use it in GitHub Desktop.
Get Active Directory groups for an user
using Novell.Directory.Ldap;
var ldapMnanger = new LDAPManager();
ldapMnanger.GetUserGroups("mihai", new LdapConnectionDetails("local.ad", "local\\user", "password"));
public class LdapConnectionDetails
{
public LdapConnectionDetails(string hostName, string username, string password, int port = 636)
{
HostName = hostName;
Port = port;
Username = username;
Password = password;
}
public string HostName { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
public class LDAPManager
{
public List<string> GetUsersInGroups(string groupName, LdapConnectionDetails connectionDetails)
{
using var ldapConnection = GetConnection(connectionDetails);
var users = SearchForUsersInGroup(groupName, ldapConnection, 0).ToList();
ldapConnection.Disconnect();
return users;
}
public void GetUserGroups(string userName, LdapConnectionDetails ldapConnectionDetails)
{
try
{
using var ldapConnection = GetConnection(ldapConnectionDetails);
var lsc = ldapConnection.Search(
"DC=local,DC=ad",
LdapConnection.ScopeSub,
"(sAMAccountName=" + userName + ")",
null,
false);
List<string> groups = new();
while (lsc.HasMore())
{
try
{
var nextEntry = lsc.Next();
var attrSet = nextEntry.GetAttributeSet();
if (attrSet.TryGetValue("memberOf", out var memberOff))
{
groups.AddRange(memberOff.StringValueArray);
}
var member = nextEntry.GetAttribute("memberOf").StringValue;
var distinguishedName = nextEntry.GetAttribute("sAMAccountName").StringValue;
}
catch (LdapException ex)
{
Console.WriteLine("Error: " + ex.ToString());
continue;
}
}
}
catch (LdapException ex)
{
Console.WriteLine("Error: " + ex.ToString()); ;
}
}
public void TestLdapConenction(LdapConnectionDetails connectionDetails)
{
using var connection = GetConnection(connectionDetails);
}
private ILdapConnection GetConnection(LdapConnectionDetails connectionDetails)
{
LdapConnectionOptions options = new LdapConnectionOptions().ConfigureRemoteCertificateValidationCallback(new System.Net.Security.RemoteCertificateValidationCallback((a, b, c, d) => true))
.UseSsl();
ILdapConnection connection = new LdapConnection(options);
connection.Connect(connectionDetails.HostName, connectionDetails.Port);
connection.Bind(connectionDetails.Username, connectionDetails.Password);
return connection;
}
private static HashSet<string> SearchForUsersInGroup(string groupName, ILdapConnection connection, int scope)
{
if (string.IsNullOrWhiteSpace(groupName))
{
throw new ArgumentException($"'{nameof(groupName)}' cannot be null or whitespace.", nameof(groupName));
}
if (connection is null)
{
throw new ArgumentNullException(nameof(connection));
}
var search = connection.Search(groupName, scope, "objectClass=*", null, false);
return QueryGroups(search);
}
private static HashSet<string> QueryGroups(ILdapSearchResults search)
{
var groups = new HashSet<string>();
if (search is not null)
{
while ((search?.HasMore()).GetValueOrDefault())
{
var nextEntry = search?.Next();
var attributeSet = nextEntry?.GetAttributeSet();
if (attributeSet is not null && attributeSet.ContainsKey("member"))
{
QueryActiveDirectoryGroups(groups, attributeSet);
}
}
}
return groups;
}
private static void QueryActiveDirectoryGroups(HashSet<string> groups, LdapAttributeSet attributeSet)
{
var atrribute = attributeSet.GetAttribute("member");
var items = atrribute?.StringValueArray?.ToList();
if (items is not null && items.Any())
{
items.ForEach(x =>
{
var parsed = x.Split(",")?.First()?.Split("=")?.Last();
if (!string.IsNullOrWhiteSpace(parsed))
{
groups.Add(parsed);
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment