Update: See an updated version of this function for .NET 2.0 here.
While I was scouring the news groups I came across an interesting piece of code that retrieves a list of the roles associated with a WindowsIdentity. The original code by Joe Kaplan was in VB.NET, here is a similar piece of code translated to C#, any bugs were probably introduced by me.
The routine uses reflection to invoke the _GetRoles method of the WindowsIdentity object to retrieve the list of roles held by the WindowsIdentity. Of course in the words of Mr. Kaplan, “You shouldn't use this in production, but it is really helpful for debugging.“
Since the code is used purely as a debugging tool I have left the error handling as an exercise for the reader :)
public static string[] GetWindowsIdentityRoles( WindowsIdentity identity )
{
object result = typeof(WindowsIdentity).InvokeMember( "_GetRoles",
BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
null, identity, new object[]{identity.Token}, null );
return (string[])result;
}
The following snippet demonstrates how to call this routine.
string
[] roles = GetWindowsIdentityRoles( WindowsIdentity.GetCurrent() );
foreach( string role in roles )
{
System.Diagnostics.Debug.WriteLine( role );
}