IsInRole Getting New Security Token

510 Views Asked by At

I'm using WindowsPrincipal's IsInRole method to check group memberships in WPF and Winforms apps. I'm generating an identity token which can be for any AD user (not necessarily the user who's actually logged into the computer--depending on what I'm doing I don't necessarily authenticate, I just use the basic informational level token (I think the proper name for it is "identity token").

The first time this code is run on a particular computer the operating system generates the identity token for the user specified. That token is then used by the IsInRole function to validate group memberships. It's fast so I really like it. However, subsequent calls to create the WindowsIdentity/WindowsPrincipal reference the existing token instead of creating a new one. The only way I know how to update the token is to log out of the computer or reboot (which clears the token cache). Does anyone know a better way to reset cached identity tokens?

Example Code C#:

Using System.Security.Principal;
WindowsIdentity impersonationLevelIdentity = new WindowsIdentity("Some_UserID_That_Isn't_Me", null);
WindowsPrincipal identityWindowsPrincipal = new WindowsPrincipal(impersonationLevelIdentity);
If (identityWindowsPrincipal.IsInRole("AN_AD_GROUP")) { ...

VB:

Imports System.Security.Principal
Dim impersonationLevelIdentity = New WindowsIdentity("Some_UserID_That_Isn't_Me", Nothing)
Dim identityWindowsPrincipal = New WindowsPrincipal(impersonationLevelIdentity)
if identityWindowsPrincipal.IsInRole("AN_AD_GROUP") then...
2

There are 2 best solutions below

0
On BEST ANSWER

Turns out I was wrong. It is caching, but it appears to be on the AD side. Eventually after I create a new identityWindowsPrincipal it gets updated to the correct group memberships.

4
On

Not sure if this may resolve your issue, try calling the dispose method of WindowsIdentity class either directly or indirectly.

using (WindowsIdentity impersonationLevelIdentity = new WindowsIdentity("Some_UserID_That_Isn't_Me", null))
{
  // your code
}