I have been sitting for this question so long and could not find an answer for it anywhere, however I know many companies are using what I want to do so I decided to put it on here.
What I would like to do is:
So here's an example:
I know my user has an entry in my database user/groups table: I know he is in the AD group called "MyAppGroup\\MyDomain". What is the easiest way to find out from my list of groups in the database to find out a user is in it?
As mentioned in the comments, the data you are looking for is already stored in Active Directory; you don't need to add it to your database at all.
You can query AD (including group membership and a ton of other data) using the System.DirectoryServices.AccountManagement API .
Here's a small example of how to retrieve the groups that a user is a member of:
using System.DirectoryServices.AccountManagement;
// ...
public List<string> GetGroupsForUser(string domain, string ou, string samAccountName)
{
var groups = new List<string>();
using (var principalContext = new PrincipalContext(ContextType.Domain, domain, ou))
using (var userPrinicpal = UserPrincipal.FindByIdentity(principalContext,
IdentityType.SamAccountName, samAccountName))
{
if (userPrinicpal == null)
return null;
foreach (var securityGroup in userPrinicpal.GetAuthorizationGroups())
groups.Add(securityGroup.DisplayName);
}
return groups;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.