pkolodziej
pkolodziej

Reputation: 1367

Declarative security demands - Is SecurityAction.Demand cached?

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?

Upvotes: 0

Views: 882

Answers (1)

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32134

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.

Upvotes: 1

Related Questions