The mysteries of WindowsPrincipal.IsInRole

WindowsPrincipal.IsInRole method is defined as the following in MSDN (https://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.isinrole(v=vs.110).aspx )

"Determines whether the current principal belongs to a specified Windows user group"

A WindowsPrincipal is basically a Windows Token wrapped in a .NET class.  Windows Tokens are generated when a Windows user (Local or Domain) is authenticated by Windows.  The IsInRole() method is similar to the Win32 API, CheckTokenMembership( https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85).aspx )  The API is used to determine whether the user is a member of the specified Windows Group (via it's Security Identifier, SID).  At the time the token is generated, Windows will create a flattened token.  This basically means that if the user is a member of a group which belongs to another group, you'll see both groups directly associated with the user's token.

The typical issue with IsInRole() is where you expect the user to be a member of the group and it returns FALSE indicating that the user is NOT a member of the group.  This means that the user is definitely not a member of the group.  To determine why this is happening you have to investigate what groups the user is a member of when their token is generated. 

  1. Do you have the correct user?  Maybe you are checking the wrong user.
  2. Is there a Domain Group Scoping Issue?  Maybe the user isn't a member of the Group
  3. Maybe the user isn't a member of the group.  Maybe the System Administrator removed the user or maybe the user was a member of the group through another group.

You are going to need to do some simple investigation to verify that in fact you have the right user and the right group.  There really is no magic going on here.

The Groups the user is a member of are stored in it's token.  They are not stored by the Group name but by their SIDs.  (I gave a hint on this from the CheckTokenMembership API).  This means that IsInRole() must convert the Group Name you are checking in IsInRole() to a SID.  It is quite possible that the SID conversion could fail. (See my previous post on this topic: https://blogs.msdn.com/b/winsdk/archive/2013/12/19/how-to-resolve-a-system-security-principal-identitynotmappedexception.aspx )

For performance reasons, if you use a SID instead, no conversion is necessary, IsInRole() can just compare SIDs.  This is going to be much faster. (https://msdn.microsoft.com/en-us/library/wak3kd03(v=vs.110).aspx )

This is all that you really need to know for IsInRole().

Follow us on Twitter, www.twitter.com/WindowsSDK