Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Users and Groups - RoleIdentity
Published: 4/17/2009
XMl / RSS

When writing applications that take advantage of Windows domain accounts for authentication, it's quite useful to be able to determine a given user's role in groups to provide or prevent access to certain features of your UI. ASP.Net provides some useful methods for determining role membership given accounts, if you are using integrated Windows authentication on your site you can access the User object exposed by the HttpContext object to determine membership. The trick here is that the User object is of type "RolePrincipal", which is ASP-based and doesn't provide the expected access to Windows account information.

So, the following code:

VB:
Dim isAdministrator As Boolean = HttpContext.Current.User.IsInRole(Environment.UserDomainName & "\Administrators")	
	
C:
bool isAdministrator = HttpContext.Current.User.IsInRole(Environment.UserDomainName + @"\Administrators");	
	

...won't return the value you might expect if you are querying for Active Directory group membership.

Instead, create a WindowsPrincipal object from the RolePrincipal object and use the same methods on that class:

So, the following code:

VB:
Dim identity As IIdentity = HttpContext.Current.User.Identity
Dim wp As WindowsPrincipal = New WindowsPrincipal(DirectCast(identity, WindowsIdentity))
Dim isAdministrator As Boolean = wp.IsInRole(Environment.UserDomainName & "\Administrators")
	
C:
IIdentity identity = HttpContext.Current.User.Identity;
WindowsPrincipal wp = new WindowsPrincipal((WindowsIdentity)identity);
bool isAdministrator = wp.IsInRole(Environment.UserDomainName + @"\Administrators");
	



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.