I am trying to use windows authentication and active directory groups to manage the security within an application. The problem I am running into is that in the code behind of a page I am trying to verify is a user hitting the ASP.NET website is a member of a specific AD group and then showing/hiding a few items based on that. The issue I am running into is that I cannot seem to get all the groups that the user is a member of in order to test. I have included the code below that I am using to list all the groups the user belongs to. This code does return a number of groups, however it is not returning all the groups. I have verified in the AD controller that all the groups appear to be set the same. Any ideas what I am doing wrong?
Private Function GetCurrentGroups() As ArrayList
Dim groups As New ArrayList()
For Each group As System.Security.Principal.IdentityReference In System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups
groups.Add(group.Translate(GetType(System.Security.Principal.NTAccount)).ToString())
Next
groups.Sort()
Return groups
End Function
You’re not doing anything wrong – you’re most likely only seeing the direct group memberships of your user.
Any nested membership –
Userbeing member ofGroupAwhich in turn is member ofGroupB– are typically not shown – so in this case, you would seeGroupAbut notGroupB.If you really need this information, you’d have to interrogate Active Directory directly (using something like the
System.DirectoryServices.AccountManagementnamespace – great MSDN article about using it).The
S.DS.AMnamespace contains among other things a classUserPrincipalrepresenting a user in AD, and this class has a method called.GetAuthorizationGroups()which will return all groups a user is member of – including nested groups.