I have been searching around for a solution on getting both users and contacts from a group in Active Directory, but cant find one.
I understand that I cant get contacts the same way as users because they are not security principals?
I use this code to get all users in my group, is it possible to extend this to retrieve name, and mobile number from contacts? Or do I need to write something new?
var context = new PrincipalContext(ContextType.Domain, "MY_DOMAIN");
using (var searcher = new PrincipalSearcher())
{
var groupName = "MY_GROUP";
var sp = new GroupPrincipal(context, groupName);
searcher.QueryFilter = sp;
var group = searcher.FindOne() as GroupPrincipal;
if (group == null)
Console.WriteLine("Invalid Group Name: {0}", groupName);
foreach (var f in group.GetMembers())
{
var principal = f as UserPrincipal;
if (principal == null || string.IsNullOrEmpty(principal.Name))
continue;
DirectoryEntry entry = (principal.GetUnderlyingObject() as DirectoryEntry);
DirectorySearcher entrySearch = new DirectorySearcher(entry);
entrySearch.PropertiesToLoad.Add("mobile");
entrySearch.PropertiesToLoad.Add("sAMAccountName");
entrySearch.PropertiesToLoad.Add("name");
SearchResultCollection results = entrySearch.FindAll();
ResultPropertyCollection rpc = results[0].Properties;
foreach (string rp in rpc.PropertyNames)
{
if (rp == "mobile")
Console.WriteLine(rpc["mobile"][0].ToString());
if(rp == "sAMAccountName")
Console.WriteLine(rpc["sAMAccountName"][0].ToString());
}
You cannot use the System.DirectoryServices.AccountManagement namespace to query contact information from Active Directory because as you point out, they are not security principles. You'll need to read and parse the member property of the group directly from the group's DirectoryEntry. This will be a list of distinguished names of all the objects which are a member of the group. There's no way to know from this what kind of object they are so you'll need to query AD for each to find out.
You have all the code needed to accomplish this already in what you posted, just add the member property to the load list and then loop though it loading new DirectoryEntry objects. The objectClass property will tell you if it's a user, group or contact.
Related
Have a scenario to verify logged in User is belong to AD Group mentioned in web.config. The code used below is working fine, but taking lot of time when looping through. (Some case User has relation of 100+ group in AD)string.
Is there a way to achieve this with direct method for better performance.
Note: I have tried Contains() method of Group obj, but could not pass string as input.
allowedRoles = "Role1, Role2"; //Read from web.config
string[] allowedRolesList = allowedRoles.Split(',');
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, UserDomain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx,IdentityType.SamAccountName,SLID);
if (user != null)
{
var groups = user.GetAuthorizationGroups();
foreach (string allowedrole in allowedRolesList)
{
foreach (GroupPrincipal group in groups)
{
if (group.Name.ToLower() == allowedrole.ToLower())
{
return true;
}
}
}
}
Looking for LDAP query to get only those OUs from Active Directory having group in it.
most important is only using LDAP query, I don't want to filter each OU using C# code.
Thanks
Groups can be stored in organizationalUnits but also in domain, containers.
Using DirectoryEntry or AccountManagement you can do the following :
Find all the groups from the domain root
Foreach group add the container property to a list of OUs
Get unique entries from the list of OUs
Here is a solution using System.DirectoryServices.AccountManagement and System.DirectoryServices
/* Retreiving a principal context
*/
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD");
/* Look for all the groups from the root
*/
GroupPrincipal allGroups = new GroupPrincipal(domainContext);
allGroups.Name = "*";
/* Bind a searcher
*/
PrincipalSearcher searcher = new PrincipalSearcher();
searcher.QueryFilter = allGroups;
PrincipalSearchResult<Principal> hRes = searcher.FindAll();
/* Read The result
*/
List<DirectoryEntry> listContainerWithGroups = new List<DirectoryEntry>();
foreach (GroupPrincipal grp in hRes)
{
DirectoryEntry deGrp = grp.GetUnderlyingObject() as DirectoryEntry;
if (deGrp != null)
listContainerWithGroups.Add(deGrp.Parent);
}
/* Get Unique Entries
*/
var listContainerWithGroupsUnique = from o in listContainerWithGroups
group o by o.Properties["distinguishedName"].Value into dePackets
select dePackets.First();
foreach (DirectoryEntry deTmp in listContainerWithGroupsUnique)
{
Console.WriteLine(deTmp.Properties["distinguishedName"].Value);
}
This isn't possible with a single search. You'll need to grab each OU and then do a one-level search of that OU for (&(objectCategory=group)(objectClass=group)). This is not going to be particuarly efficient when you consider how many searches you might need to perform. Also consider whether or not you need to handle the scenario where you have OU=A\OU=B. If OU=B includes the group, do you include OU=A (the parent)?
I've an Active Directory with domain myDomain.local, under it there exists a Distribution Group that contains many groups.
How can I read (programmatically) all these subgroups to retrieve a list of their names ?
And how to optimize the query to filter the result so that it just retrieves all the groups that ends with the word Region ?
BTW, I'm using C#.Net, ASP.Net and sharepoint, and i'm not experienced with AD.
If you're on .NET 3.5 (or can upgrade to it), you can use this code using the System.DirectoryServices.AccountManagement namespace:
// create the "context" in which to operate - your domain here,
// as the old-style NetBIOS domain, and the container where to operate in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "cn=Distribution Group,dc=YourDomain,dc=local");
// define a "prototype" - an example of what you're searching for
// Here: just a simple GroupPrincipal - you want all groups
GroupPrincipal prototype = new GroupPrincipal(ctx);
// define a PrincipalSearcher to find those principals that match your prototype
PrincipalSearcher searcher = new PrincipalSearcher(prototype);
// define a list of strings to hold the group names
List<string> groupNames = new List<string>();
// iterate over the result of the .FindAll() call
foreach(var gp in searcher.FindAll())
{
// cast result to GroupPrincipal
GroupPrincipal group = gp as GroupPrincipal;
// if everything - grab the group's name and put it into the list
if(group != null)
{
groupNames.Add(group.Name);
}
}
Does that satisfy your needs?
For more info on the System.DirectoryServices.AccountManagement namespace, read the Managing Directory Security Principals in the .NET Framework 3.5 article in MSDN magazine.
Here's the solution I made; for those who are interested:
public ArrayList getGroups()
{
// ACTIVE DIRECTORY AUTHENTICATION DATA
string ADDomain = "myDomain.local";
string ADBranchsOU = "Distribution Group";
string ADUser = "Admin";
string ADPassword = "password";
// CREATE ACTIVE DIRECTORY ENTRY
DirectoryEntry ADRoot
= new DirectoryEntry("LDAP://OU=" + ADBranchsOU
+ "," + getADDomainDCs(ADDomain),
ADUser,
ADPassword);
// CREATE ACTIVE DIRECTORY SEARCHER
DirectorySearcher searcher = new DirectorySearcher(ADRoot);
searcher.Filter = "(&(objectClass=group)(cn=* Region))";
SearchResultCollection searchResults = searcher.FindAll();
// ADDING ACTIVE DIRECTORY GROUPS TO LIST
ArrayList list = new ArrayList();
foreach (SearchResult result in searchResults)
{
string groupName = result.GetDirectoryEntry().Name.Trim().Substring(3);
list.Add(groupName);
}
return list;
}
public string getADDomainDCs(string ADDomain)
{
return (!String.IsNullOrEmpty(ADDomain))
? "DC=" + ADDomain.Replace(".", ",DC=")
: ADDomain;
}
I have a question about determining the type (User or Group) of a account name.
For example, I have two strings, say "Adventure-works\david" and "Adventure-works\admins",
the first represents a user named david, and the second represents an AD group.
My question is how can I determin the type(User or AD group) of these account? Are there convenient method I can use?
Any comments are appreciated.
Thanks.
What version of .NET are you on??
If you're on .NET 3.5, see this excellent MSDN article on how the Active Directory interface has changed quite a bit.
If you're on .NET 3.5, you could write:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
Principal myObject = Principal.FindByIdentity(ctx, "your name value");
Typically, you'd have to pass in just the user name - the part after the backslash - not the whole DOMAIN\USERNAME string.
This "Principal" now either is a UserPrincipal or a GroupPrincipal (or it could some other type of principal, e.g. ComputerPrincipal):
if(myObject is UserPrincipal)
{
// you have a user
}
else if(myObject is GroupPrincipal)
{
// you have a group
}
and you can go on from there.
If you're on .NET 1.x/2.0/3.0, you'd have to use the slightly more involved procedure of creating a DirectorySearcher and searching for your object:
// create root DirectoryEntry for your search
DirectoryEntry deRoot = new DirectoryEntry("LDAP://dc=YourCompany,dc=com");
// create searcher
DirectorySearcher ds = new DirectorySearcher(deRoot);
ds.SearchScope = SearchScope.Subtree;
// define LDAP filter - all you can specify is the "anr" (ambiguous name
// resolution) attribute of the object you're looking for
ds.Filter = string.Format("(anr={0})", "YourNameValue");
// define properties you want in search result(s)
ds.PropertiesToLoad.Add("objectCategory");
ds.PropertiesToLoad.Add("displayName");
// search
SearchResult sr = ds.FindOne();
// check if we get anything back, and if we can check the "objectCategory"
// property in the search result
if (sr != null)
{
if(sr.Properties["objectCategory"] != null)
{
// objectType will be "Person" or "Group" (or something else entirely)
string objectType = sr.Properties["objectCategory"][0].ToString();
}
}
Marc
Warning: In case of using DirectorySearcher the accepted answer might fail, since objectCategory it doesn't return consistent results.
Consider using objectClass instead:
SearchResult sr = ds.FindOne();
bool isUser = sr.Properties["objectClass"]?.Contains("user") == true;
// OR
bool isGroup = sr.Properties["objectClass"]?.Contains("group") == true;
using System.DirectoryServices.AccountManagement;
...
..
Principal myPrincipal = Principal.FindByIdentity(ctx, "your name value");
if (myPrincipal.GetType() == typeof(GroupPrincipal)) {
GroupPrincipal myGroup = (GroupPrincipal)myPrincipal;
} else {
UserPrincipal myUser = (UserPrincipal)myPrincipal;
}
I have code that searches for all users in a department:
string Department = "Billing";
DirectorySearcher LdapSearcher = new DirectorySearcher();
LdapSearcher.PropertiesToLoad.Add("displayName");
LdapSearcher.PropertiesToLoad.Add("cn");
LdapSearcher.PropertiesToLoad.Add("department");
LdapSearcher.PropertiesToLoad.Add("title");
LdapSearcher.PropertiesToLoad.Add("memberOf");
LdapSearcher.Filter = string.Format("(&(objectClass=user)(department={0}))", Department);
SearchResultCollection src = LdapSearcher.FindAll();
What would the filter need to look like if I only wanted everyone in the "Manager Read Only" AD Group?
Am I going about this all wrong?
Looking at your search I have a couple of points for you. First, the search uses objectClass (non-indexed) instead of objectCategory (indexed). Huge performance issue with that query. You would most always want to combine the two together depending on what you are trying to retrieve:
(&(objectCategory=person)(objectClass=user)) = All users (no contacts)
(&(objectCategory=person)(objectClass=contact)) = All contacts (no users)
(&(objectCategory=person)) = All users and contacts
As for looking up the users in a group you can enumerate the list of member objects of the specific group. In the member attribute of the group object is the distinguishedName of each user.
This article describes enumerating members of a group...
Don't forget that you may have to handle nested groups of the parent group, as there isn't a default way to handle this with LDAP queries. For that you may need to evaluate if the member object is a group and then get the member attribute for that child group.
Lastly, you should get in the habit of specifying a dns prefix to your query.
Without DNS prefix:
LDAP://ou=ouname,dc=domain,dc=com
With DNS prefix (all three work):
LDAP://servername/ou=ouname,dc=domain,dc=com
LDAP://servername.domain.com/ou=ouname,dc=domain,dc=com
LDAP://domain.com/ou=ouname,dc=domain,dc=com
A single domain won't cause you much issue but when you try and run a search in a multiple domain environment you will get bitten without this addition. Hope this helps move you closer to your goal.
I've always found Howto: (Almost) Everything In Active Directory via C# helps for most AD questions.
If you know the AD path to the group already it would probably be easier to open a DirectoryEntry on that, then do a DirectorySearcher from there.
using (DirectoryEntry de = new DirectoryEntry("LDAP://somedomain/CN=FooBar"))
{
DirectorySearcher search = new DirectorySearcher(de, ("(objectClass=user)"));
}
There is also a flag on the Searcher for whether to drill down to sub containers, I forget the name off hand.
I use following code (from http://blogs.technet.com/b/brad_rutkowski/archive/2008/04/15/c-getting-members-of-a-group-the-easy-way-with-net-3-5-discussion-groups-nested-recursive-security-groups-etc.aspx) it works fine.
IList<string> getMembers(string domainName, string groupName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);
if (grp == null) {
throw new ApplicationException("We did not find that group in that domain, perhaps the group resides in a different domain?");
}
IList<string> members = new List<String>();
foreach (Principal p in grp.GetMembers(true))
{
members.Add(p.Name); //You can add more attributes, samaccountname, UPN, DN, object type, etc...
}
grp.Dispose();
ctx.Dispose();
return members;
}
//Search for Group and list group members
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices.AccountManagement;
namespace ExportActiveDirectoryGroupsUsers
{
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null, useage: ExportActiveDirectoryGroupsUsers OutputPath"); // Check for null array
}
else
{
Console.Write("args length is ");
Console.WriteLine(args.Length); // Write array length
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Console.Write("args index ");
Console.Write(i); // Write index
Console.Write(" is [");
Console.Write(argument); // Write string
Console.WriteLine("]");
}
try
{
using (var ServerContext = new PrincipalContext(ContextType.Domain, ServerAddress, Username, Password))
{
/// define a "query-by-example" principal - here, we search for a GroupPrincipal
GroupPrincipal qbeGroup = new GroupPrincipal(ServerContext, args[0]);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
// find all matches
foreach (var found in srch.FindAll())
{
GroupPrincipal foundGroup = found as GroupPrincipal;
if (foundGroup != null)
{
// iterate over members
foreach (Principal p in foundGroup.GetMembers())
{
Console.WriteLine("{0}|{1}", foundGroup.Name, p.DisplayName);
// do whatever you need to do to those members
}
}
}
}
//Console.WriteLine("end");
}
catch (Exception ex)
{
Console.WriteLine("Something wrong happened in the AD Query module: " + ex.ToString());
}
Console.ReadLine();
}
}
}
}