Search Users in Specific OU Active Directory - c#

I have different OU in my Active Directory for different users, I want to get all users of a specific OU using C#.
Currently I have this filter, but it returns all users from all OU
(&(objectClass=User)(objectCategory=Person))
Kindly help me in finding users of specific user using ldap

You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
// LDAP string to define your OU
string ou = "OU=Sales,DC=YourCompany,DC=com";
// set up a "PrincipalContext" for that OU
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Yourcompany.com", ou))
{
// define the "query-by-example" user (or group, or computer) for your search
UserPrincipal qbeUser = new UserPrincipal(ctx);
// set whatever attributes you want to limit your search for, e.g. Name, etc.
qbeUser.Surname = "Smith";
// define a searcher for that context and that query-by-example
using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
{
foreach (Principal p in searcher.FindAll())
{
// Convert the "generic" Principal to a UserPrincipal
UserPrincipal user = p as UserPrincipal;
if (user != null)
{
// do something with your found user....
}
}
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.
Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:
DisplayName (typically: first name + space + last name)
SAM Account Name - your Windows/AD account name
User Principal Name - your "username#yourcompany.com" style name
You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher.

One option is to just set the organization unit (OU) when you create your DirectoryEntry object:
using (var entry = new DirectoryEntry($"LDAP://OU={unit},OU=Accounts,DC={domain},DC=local"))
{
// Setup your search within the directory
var search = new DirectorySearcher(entry)
{
Filter = "(&(objectCategory=person)(objectClass=user)(memberOf=*))"
};
// Set the properties to be returned
search.PropertiesToLoad.Add("SamAccountName");
// Get the results
var results = search.FindAll();
// TODO Process the results as needed...
}

Related

Exception while fetching data from Active Directory via C#

We are using the foll. code to retrieve the AD users and their details:-
We get error at line: SearchResultCollection resultCol =
search.FindAll();
Exception is: DirectoryServiceCOMException: An operations error
occurred. at System.DirectoryServices.DirectoryEntry.Bind(Boolean
throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject() at
System.DirectoryServices.DirectorySearcher.FindAll(Boolean
findMoreThanOne) at
SharePointProject20.VisualWebPart1.VisualWebPart1.GetADUsers()
public List<Users> GetADUsers()
{
try
{
List<Users> lstADUsers = new List<Users>();
string DomainPath = "LDAP://DC=SYSDOM,DC=local";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("usergroup");
search.PropertiesToLoad.Add("displayname");//first name
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString = string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname") &&
result.Properties.Contains("mail") &&
result.Properties.Contains("displayname"))
{
Users objSurveyUsers = new Users();
objSurveyUsers.Email = (String)result.Properties["mail"][0] +
"^" + (String)result.Properties["displayname"][0];
objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
lstADUsers.Add(objSurveyUsers);
}
}
}
return lstADUsers;
}
catch (Exception ex)
{
return null;
}
}
public class Users
{
public string Email { get; set; }
public string UserName { get; set; }
public string DisplayName { get; set; }
public bool isMapped { get; set; }
}
What could be the issue?
Our domain name is SYSDOM.local
Could it be related to permissions (how do I verify this with network admin guys?), or do I need to explicitly pass username/password?
Code reference: http://www.codeproject.com/Tips/599697/Get-list-of-Active-Directory-users-in-Csharp
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for a UserPrincipal
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.
Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:
DisplayName (typically: first name + space + last name)
SAM Account Name - your Windows/AD account name
User Principal Name - your "username#yourcompany.com" style name
You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher.
Constructing the PrincipalContext like shown in the sample will automatically connect to the current AD domain with the current user credentials. If you need to, you can specify other containers or domains to bind to, or you can also supply alternative credentials by using other overloads of the PrincipalContext constructor
The issue was resolved after using the HostingEnvironment.Impersonate() in PageLoad:-
Example:
using (HostingEnvironment.Impersonate()) {
GetADUsers();
}

Using Active Directory to determine what is displayed on a page

I am rather new to C#. I want to display one set of fields if the user who is logged in is a member of the Administration Board and another set of fields if the user is not a member of the Administration Board.
The manager has instructed me to use Active Directory to do this.
Is there an example someone can point me to that I can review?
Is there a way for me to write a page (just for my own review) that will display all the user groups this organization has in Active Directory?
Here is one way of doing an Active Directory query that gets all domain users, a specific user's groups, and whether a user belongs to a group:
public static List<string> DomainUsers
{
get
{
List<string> users = new List<string>();
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain"))
{
// find user by display name
UserPrincipal user = new UserPrincipal(ctx);
PrincipalSearcher search = new PrincipalSearcher(user);
search.FindAll().Cast<UserPrincipal>().ToList().ForEach(u => users.Add(u.SamAccountName));
}
return users;
}
}
/// <summary>
/// Gets all associated group names for current user on the current domain
/// </summary>
/// <returns></returns>
public static List<string> GetGroupNames(string username)
{
var pc = new PrincipalContext(ContextType.Domain, "domain");
var src = UserPrincipal.FindByIdentity(pc, username).GetGroups(pc);
var result = new List<string>();
src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
return result;
}
public static bool UserBelongsToGroup(string group)
{
PrincipalContext pc = new PrincipalContext((Environment.UserDomainName == Environment.MachineName ? ContextType.Machine : ContextType.Domain), Environment.UserDomainName);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, group);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, Environment.UserName);
return up.IsMemberOf(gp);
}
Please note that you will need to use the System.DirectoryServices.AccountManagement namespace which can be found in the .NET 4.0 framework assemblies when adding a reference. You will need to be targetting .NET 4.0 to use this namespace.
Use IsInRole() method. It is in System.Principle namespace - as far as I remember.

List users in active directory domain AND subdomain

We have an AD with users in "mydomain.com" and users in "child.mydomain.com". When We try to list them, we can only find the "mydomain.com"'s users and groups, but we also need those from the child domain. How can I achieve this using C# ? Please take a look to my sample code :
context = new PrincipalContext(ContextType.Domain);
//...
var filter = new GroupPrincipal(context);
filter.IsSecurityGroup = true;
using(var searcher = new PrincipalSearcher(filter)
using(var results = searcher.FindAll())
{
foreach(GroupPrincipal group in results)
{
string path = "LDAP://rootDSE";
DirectoryEntry searchRoot = new DirectoryEntry(path);
string configNC = searchRoot.Properties["configurationNamingContext"].Value.ToString();
DirectoryEntry configSearchRoot = new DirectoryEntry("LDAP://" + configNC);
DirectorySearcher configSearch = new DirectorySearcher(configSearchRoot);
configSearch.Filter("(NETBIOSName=*)");
configSearch.PropertiesToLoad.Add("dnsroot");
configSearch.PropertiesToLoad.Add("ncname");
configSearch.PropertiesToLoad.Add("NETBIOSName");
SearchResultCollection forestPartitionList = configSearch.FindAll();
List<Tuple<string,string>> netbiosNameList = new List<Tuple<string,string>>(forestPartitionList.Count);
foreach(SearchResult domainPartition in forestPartitionList)
{
string ncname = domainPartition.Properties["ncname"][0].ToString();
string netBIOSName = domainPartition.Properties["NETBIOSName"][0].ToString();
netbiosNameList.Add(Tuple.Create(ncname, netBIOSName));
}
//...
//Find group members
using (var principal = GroupPrincipal.FindByIdentity(context, IdentityType.DistinguishedName, group.DistinguishedName))
using (var members = principal.GetMembers(true))
using (var enumerator = members.GetEnumerator())
{
//...
}
}
}
The code is not exactly written this way, I just want to show you the main calls that are made to query the AD. We can list the parent domain groups and users but not the child domain ones. If I change the initialization of my "context" variable passing the child domain IP and user/password, I can list the groups and users in it. But we want to be able to do so while being in the parent domain.
I hope you can help me. Thanks a lot!
You can query the global catalog.
It contains a read-only, searchable, partial representation of every object in every domain in a multidomain Active Directory forest.
The GC operates on port 3268 ( standard ldap ) and 3269 ( SSL ldap ). Simply connect to any of your domain controllers on one of the above two ports and your search will be automatically directed to the GC server.
To perform any modifications, though, you will have to send such request to a domain controller for that particular domain the object belongs to.

Get just the Enabled Accounts from Active Directory

I am using System.DirectoryServices.AccountManagement.dll to deal with Active Directory
to get all the users in the "Domain Users" group.
This is returning all the users in the domain but I need to get just the enabled ones.
Here is some sample code:
List<string> users = new List<string>();
PrincipalContext pcContext = GetPrincipalContext();
GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcContext,
IdentityType.Name,
"Domain Users");
foreach (Principal user in grp.GetMembers(true).OfType<UserPrincipal>())
{
if (user.Enabled != false)
{
users.Add(user.Name);
}
}
Other groups work fine, but when the group is "Domain Users", the value of the Enabled property is false for all users. This makes it impossible to distinguish between enabled and disabled users without doing a further query for each user.
UserPrinciple objects have a bool Enabled property for this.
http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal_properties.aspx
// Add this to GetUserDetails
objUserDetails.EmployeeId = UserPrinical.EmployeeId;
// Then condition the add to only add enabled
if (objUserDetails.Enabled) {
objUserDetails.Add(GetUserDetails(p.Name));
}
A method around this problem could be to first search for Enabled Users using the PrincipalSearcher class and then use the Principal's method of IsMemberOf()
List<string> users = List<string>();
PrincipalContext pcContext = GetPrincipalContext();
GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcContext, IdentityType.Name, "Domain Users");
UserPrincipal searchFilter = new UserPrincipal(pcContext){ Enabled = true }
PrincipalSearcher searcher = new PrincipalSearcher(searchFilter);
PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (Principal user in results)
if (user.IsMemberOf(grp))
users.Add(user.SamAccountName);
There's a remark on the MSDN page of the Enabled property saying :
If the principal has not been persisted in the store, this property returns null. After the principal is persisted, the default enabled setting depends on the store. The AD DS and AD LDS stores disable new principals when they are persisted, whereas SAM enables new principals when they are persisted. The application can only set this property to a value after it has been persisted in the store.
Perhaps it's related if the default is false ?
Also, there's a post on the MSDN forum about UserPrincipal.Enabled returns False for accounts that are in fact enabled? and that really sound similar to your issue. According to the post there's perhaps a solution here :
I think I misunderstood. Disregard what I posted before. I think I
know what's happening. The GetMembers method apparently isn't loading
the UserPrincipal data. I don't know if there is a better solution,
but the following works (at least on my AD):
foreach (UserPrincipal user in group.GetMembers(false))
{
UserPrincipal tempUser = UserPrincipal.FindByIdentity(context, user.SamAccountName);
// use tempUser.Enabled
// other code here
}

How do I set the ManagedBy property on a GroupPrincipal

I'm creating and updating Groups in Active Directory using the GroupPrincipal class in System.DirectoryServices.AccountManagement. When creating and updating, I also need to be able to set the ManagedBy property that you are able to set in the Managed By tab in the groups properties in the AD management console.
Can it be done programatically?
You cannot do this directly, unfortunately - but you can get access to the underlying DirectoryEntry and do it there:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
UserPrincipal toBeModified = UserPrincipal.FindByIdentity(".....");
UserPrincipal manager = UserPrincipal.FindByIdentity(ctx, "......");
DirectoryEntry de = toBeModified.GetUnderlyingObject() as DirectoryEntry;
if (de != null)
{
de.Properties["managedBy"].Value = manager.DistinguishedName;
toBeModified.Save();
}
You could extend the GroupPrincipal class and provide a ManagedBy property using the ExtensionSet method.
Take a look at this page. This is one of the best tutorials on AD in c#.
Some code that should work(untested) :
string connectionPrefix = "LDAP://" + ouPath;
DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
DirectoryEntry newGroup = dirEntry.Children.Add
("CN=" + groupName, "group");
group.Properties["sAmAccountName"].Value = groupName;
newGroup.Properties["managedBy"].Value = managerDistinguishedName;
newGroup.CommitChanges();
dirEntry.Close();
newGroup.Close();

Categories

Resources