Declarative Security Requirements - Is SecurityAction.Demand Secure?
I'm having trouble 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);
}
Call code:
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.");
}
The default user is NOT a member of LocalTestGroup. The user specified by a member of the IS LocalTestGroup token.
Problem:
The first call to LocalTestGroupOnly () succeeds because the user specified an IS member of the LocalTestGroup token. The second call (as the 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 succeeds as well.
If I run the program individually - with and without impersonation, the behavior is correct for us: it manages to impersonate "Test" and fail when called as the default user.
What is the problem?
source to share
Can't you check Thread.CurrentPrincipal.Identity
instead WindowsIdentity.GetCurrent()
? PrincipalPermission.Demand()
uses the first one.
To change Thread.CurrentPrincipal
(or HttpContext.User
) it seems like you have to set them explicitly after impersonation or after cancellation. Check here for a similar question.
source to share