views:

154

answers:

1

Hi

I am having a trouble during impersonating a user. I have a method declared like this:

[PrincipalPermission(SecurityAction.Demand, Name=@"DJPITER-PC\Test", Role="LocalTestGroup")]
static void LocalTestGroupOnly()
{
    Console.WriteLine("Inside LocalTestGroupOnly() - {0}", 
        WindowsIdentity.GetCurrent().Name);
}

The calling code is:

WindowsImpersonationContext context = 
        WindowsIdentity.Impersonate(token);

    Console.WriteLine("Calling LocalTestGroupOnly() as {0}", 
        WindowsIdentity.GetCurrent().Name);
    LocalTestGroupOnly();

    context.Undo();

    try
    {
        // Reverted user is displayed properly 
        Console.WriteLine("Calling LocalTestGroupOnly() as {0}", 
            WindowsIdentity.GetCurrent().Name);

        // This method should fail but if succeeds
        LocalTestGroupOnly();
    }
    catch (SecurityException ex)
    {
        Console.WriteLine("Your account lacks permission to that function.");
    }

Default user is NOT member of LocalTestGroup. User indicated by token IS member of LocalTestGroup.

The problem:

The first call to LocalTestGroupOnly() succeeds because user indicated by the token IS member of LocalTestGroup. The second call (as default user) to LocalTestGroupOnly() should fail because the default user is not 'Test' and it does not belong to LocalTestGroup. The problem is that this method also succeeds.

If I run the program separately - with and without impersonation the behaviour us correct: it succeeds when impersonating as 'Test' and fails when calling as default user.

What is the problem over here?

Kind Regards PK

+1  A: 

Could you check Thread.CurrentPrincipal.Identity instead of WindowsIdentity.GetCurrent()? PrincipalPermission.Demand() uses the first.

To change Thread.CurrentPrincipal (or HttpContext.User) it seems that you have to set them explicitly after impersonation or after an undo. Check here for a similar question.

Ronald Wildenberg
Indeed: after context.Undo() I had to add Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());Why didn't the Undo() method do that? It seems that I dont fully understand the Thread.CurrentPrincipal and WindowsImpersonationContext ...
pkolodziej
I looked up some examples and they all explicitly set Thread.CurrentPrincipal when impersonating. I added some more info to my answer.
Ronald Wildenberg
Thanks - have a good day.
pkolodziej