I have a pretty simple task – given the list (from file) of user names and their emails, synchronize it with the members of AD (Active Directory) users, meaning – add users that exist in the list and missing in AD group, and remove users that exist in AD group and missing in the list. The complication is that the company is very big and uses a lot of domains around the world based on their location – let’s say it.comany.com, fr.company.com, uk.company.com, us.company.com, etc. – each of them contains tons of users and users to add can be in any of them.
I use the following code to find the AD group:
var groupSearch = new DirectorySearcher(new DirectoryEntry(“LDAP://company.com”), “(&(ObjectClass=Group)(CN=TheNameOfTheADGroup))”);
var dirEntry = new DirectoryEntry(groupSearch.FindOne().Path);
and it finds the group successfully.
Now, I need to add user to this group (knowing only his username, like willsmith). This can be done by calling
dirEntry.Invoke(“Add”, new object[] { dirPath })
where dirPath is the FULL LDAP path of the user. I can get it by searching in specific domain, e.g.:
var userSearch = new DirectorySearcher(new DirectoryEntry(“LDAP://xx.company.com”), “(&(ObjectClass=User)(CN=willsmith))”);
var dirPath = userSearch.FindOne().Path;
//and then use dirPath in Invoke(“Add”…) – see above
but the problem is that I don’t know which exact domain the user is in, and the number of domains is around 30, each user search takes about 2-3 seconds, so it will be a very long process.
Any ideas how to define domain for the user? Or maybe some other solution for the problem?
P.S. I do not use the new AD management capabilities introduced in .NET 3.5 (PrincipalContext, GroupPrincipal.FindByIdentity), because they don’t allow to specify the root for the search (which was the first parameter in DirectorySearcher constructor), which I need because the AD group is located in company.com domain not us.company.com from where is my account.
Related
I am creating Active Directory groups in my app. I make security and distribution groups. The groups will get created just fine, but it takes about 10-15 minutes to show up in the Active Directory Users and Computers.
Is there some kind of forced sync I can perform in C# to make this happen sooner? Or maybe some setting I can change in my directory to change this behavior?
Example code
DirectoryEntry ou1= topLevel.Children.Find("OU=ou1");
DirectoryEntry secGroups = ou1.Children.Find("OU=Security Groups");
DirectoryEntry newGroup = secGroups.Children.Add("CN=" + name + "", "group");
newGroup.CommitChanges();
GroupPrincipal createdGroup = GroupPrincipal.FindByIdentity(this._context, name);
createdGroup.SamAccountName = name;
createdGroup.DisplayName = name;
createdGroup.GroupScope = GroupScope.Universal;
createdGroup.Save();
if (members.Any())
{
foreach (var item in members)
{
createdGroup.Members.Add(this._context, IdentityType.SamAccountName, item);
}
createdGroup.Save();
}
Using ASP.NET MVC, C#, System.DirectoryServices.AccountManagement, System.DirectoryServices.ActiveDirectory.
The most likely answer is that it takes time to propagate to all domain controllers on your network. You may be connected to a different DC via ADUC from the one your application updated.
Something that might help in this situation where you have multiple domain controllers replicating is to target a specific DC for each call you make to the AD server.
So instead of "LDAP://mydomain.com" it becomes something like "LDAP://myDC.mydomain.com"
I am querying my Azure AD graph API for a user's group memberships.
I can make the query just fine, but the results are only the groups that the user DIRECTLY belongs to. None of the nested groups are listed.
I'm trying to find out if a user belongs to a specific group, but I don't want to have to make, what could end up to be, over 100 api calls to find out. (i.e. a user belongs to GroupA which is a member of GroupB which is a member of GroupC which is a member of GroupD. Groups B, C, and D do not show up in the user's list of groups even though he technically belongs to them - only GroupA).
Is there any way to get ALL group memberships in one API call or another? When I was using Integrated Windows Authentication, the IsInRole(GroupD) would have returned true. Though, that is not available with Azure AD authentication and any of the postings that claim to have code to re-implement IsInRole are simply making the same call to user.memberOf (which does not do the nested groups).
Just for reference, this is the code where I make the call.
var client = AuthenticationHelper.GetActiveDirectoryClient();
var user = await client.Users.GetByObjectId(objectId).ExecuteAsync();
var userFetcher = (IUserFetcher)user;
var pagedCollection = await userFetcher.MemberOf.ExecuteAsync();
do
{
var directoryObjects = pagedCollection.CurrentPage.ToList();
foreach (var group in directoryObjects.OfType<Group>().Select(directoryObject => directoryObject))
{
groupMembership.Add(group);
}
pagedCollection = await pagedCollection.GetNextPageAsync();
}
while (pagedCollection != null && pagedCollection.MorePagesAvailable);
Yes. The getMemberObjects API returns all groups (transitive) of which the user is a member: https://msdn.microsoft.com/en-us/library/azure/dn835117.aspx . Also, using the checkMemberGroups API you can check whether or not the user is member of a group (transitively): https://msdn.microsoft.com/en-us/library/azure/dn835107.aspx
However for your requirement the application roles feature of Azure AD might be a better fit. Your application can declare application roles, that can be assigned by the admin to users as well as groups. When the users signs in to your application, Azure AD computes the application roles that have been assigned to them and sends them in the roles claim. No need to query graph at runtime. See here: http://www.dushyantgill.com/blog/2014/12/10/roles-based-access-control-in-cloud-applications-using-azure-ad/
I am working on a web application, ASP.NET, C#. Users are required to log in using an account local to the machine the app is running on, which I'll call "cyclops" for this example. I want the app to be able to query the local directory of users and groups to determine what groups the user is in. The code looks something like this:
DirectoryEntry entry = new DirectoryEntry("WinNT://cyclops/Users", "SomeServiceAccount",
"SvcAcctP#$$word", AuthenticationTypes.Secure);
entry.RefreshCache();
// Etc.
My two problems are:
That's pretty clearly not the correct path to use, but my research
and experimentation hasn't found the right answer. This MSDN
article talks about local paths, but doesn't fill in the blanks.
Do I use "LDAP://cyclops/Users", "WinNT://localhost/Users",
"WinNT://cyclops/cn=Users"?
As you can see, I'm providing the
credentials of a local service account. That account needs
permission to access the local directory, but I have no idea where
to set those permissions. Is it a specific file somewhere? Does
the account need to be a member of a particular group?
My experimentation has produced many errors: "The group name could not be found.", "The provider does not support searching...", "The server is not operational.", "Unknown error (0x80005004)", etc.
Thank you for your time...
-JW
WinNT requires the following format
WinNT://<domain/server>/<object name>,<object class>
To get groups of a given user, use
using (DirectoryEntry user = new DirectoryEntry("WinNT://./UserAccount,user"))
{
foreach(object group in (IEnumerable)user.Invoke("Groups",null))
{
using(DirectoryEntry g = new DirectoryEntry(group))
{
Response.Write(g.Name);
}
}
}
where
UserAccount is a name of required user.
dot stands for current machine (you can replace it with cyclops or use Environment.MachineName)
user credentials ("SomeServiceAccount", "SvcAcctP#$$word") might be required, depends on setup
To get users in a particular group, use
using (DirectoryEntry entry = new DirectoryEntry("WinNT://./Users,group"))
{
foreach (object member in (IEnumerable)entry.Invoke("Members"))
{
using(DirectoryEntry m = new DirectoryEntry(member))
{
Response.Write(m.Name);
}
}
}
where
Users is a name of group
I'm using the System.DirectoryServices.AccountManagement to provide user lookup functionality.
The business has several region specific AD domains: AMR, EUR, JPN etc.
The following works for the EUR domain, but doesn't return users from the other domains (naturally):
var context = new PrincipalContext(ContextType.Domain, "mycorp.com", "DC=eur,DC=mycorp,DC=com");
var query = new UserPrincipal(GetContext());
query.Name = "*Bloggs*";
var users = new PrincipalSearcher(query).FindAll().ToList();
However, if I target the entire directory, it doesn't return users from any of the region specific domains:
var context = new PrincipalContext(ContextType.Domain, "mycorp.com", "DC=mycorp,DC=com");
How do I search the entire directory?
Update
Read up on "How Active Directory Searches Work":
http://technet.microsoft.com/en-us/library/cc755809(v=ws.10).aspx
If I suffix the server name with port 3268 it searches against the Global Catalog:
var context = new PrincipalContext(ContextType.Domain, "mycorp.com:3268", "DC=mycorp,DC=com");
However it's very, very slow. Any suggestions on how to improve performance?
Queries which have initial wildcards (*Bloggs*) will be slow unless you have a tuple index on the attribute being queries. None of the attributes in AD have this set by default. Better to not do initial wildcards.
In my Sharepoint code I display a list of all defined users via:
foreach (SPUser user in SPContext.Current.Web.AllUsers)
{
...
}
The great part is, I can add a domain security group to a Sharepoint group (like Visitors) thus adding many users at once (simpler administration). But my code doesn't see those users at least not until they log-in for the first time (if they have sufficient rights). In this case I can only see the domain security group SPUser object instance with its IsDomainGroup set to true.
Is it possible to get domain group members by means of Sharepoint without resorting to Active Directory querying (which is something I would rather avoid because you probably need sufficient rights to do such operations = more administration: Sharepoint rights + AD rights).
You can use the method SPUtility.GetPrincipalsInGroup (MSDN).
All parameters are self-explaining except string input, which is the NT account name of the security group:
bool reachedMaxCount;
SPWeb web = SPContext.Current.Web;
int limit = 100;
string group = "Domain\\SecurityGroup";
SPPrincipalInfo[] users = SPUtility.GetPrincipalsInGroup(web, group, limit, out reachedMaxCount);
Please note that this method does not resolve nested security groups. Further the executing user is required to have browse user info permission (SPBasePermissions.BrowseUserInfo) on the current web.
Update:
private void ResolveGroup(SPWeb w, string name, List<string> users)
{
foreach (SPPrincipalInfo i in SPUtility.GetPrincipalsInGroup(w, name, 100, out b))
{
if (i.PrincipalType == SPPrincipalType.SecurityGroup)
{
ResolveGroup(w, i.LoginName, users);
}
else
{
users.Add(i.LoginName);
}
}
}
List<string> users = new List<string>();
foreach (SPUser user in SPContext.Current.Web.AllUsers)
{
if (user.IsDomainGroup)
{
ResolveGroup(SPContext.Current.Web, user.LoginName, users);
}
else
{
users.Add(user.LoginName);
}
}
Edit:
[...] resorting to Active Directory querying (which is something I would rather avoid because you probably need sufficient rights to do such operations [...]
That's true, of course, but SharePoint has to lookup the AD as well. That's why a application pool service account is required to have read access to the AD.
In other words, you should be safe executing queries against the AD if you run your code reverted to the process account.
I would suggest you just query Active Directory directly. You are spending a lot of effort to try to get SharePoint to make this call to AD for you. Every account that has Domain User access should be able to query the AD groups you have nested in SharePoint. I would just go to the source.
This way you don't have to worry about Browse User Permissions or anything else. In my opinion trying to proxy this through SharePoint is just making your life more difficult.