Query active directory to get a user's roles in .NET
Solution 1
Have you taken a look at this?
Solution 2
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// find the roles....
var roles = user.GetAuthorizationGroups();
// enumerate over them
foreach (Principal p in roles)
{
// do something
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:
cbp
Updated on July 12, 2022Comments
-
cbp over 1 year
I have been using Linq to Active Directory a bit but I am finding it difficult to get a list of all roles of which the user is a member. I can retrieve a list of their immediate groups but it isn't recursive.
The reason I am trying to query AD directory is to work around the built-in Role Manager AspNetWindowsTokenRoleProvider which won't let you call Roles.GetRolesForUser(username) unless the username matches the current Windows Identity.
-
pashute about 8 yearsThe next answer by @marc_s gives you a simple method to see the Active Directory groups. This answer maps the AD groups to a read-only ActiveDirectoryMembershipProvider.RoleProvider that returns 'System.Web.Security.Role' objects, and the following methods: GetRolesForUser(username), GetUsersInRole(rolename), GetAllRoles(), IsUserInRole(user, role), RoleExists(rolename)
-
RandomHandle about 6 yearsI was testing this in a simple console app and figured out I needed to add a reference to
System.DirectoryServices.AcccountManagement
before I could get any of the code to work.