I have been playing around with identity and principal when I noticed that the method I added
[PrincipalPermission(SecurityAction.Deny, Role = "Admin")]
with an identity of
GenericIdentity identity = new GenericIdentity("JC", "Type1");
GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "Admin", "User" });
Thread.CurrentPrincipal = principal;
still gets invoked without throwing SecurityException as it would if it had a Demand security action.
In fact even if I have misspelled the Role like so
[PrincipalPermission(SecurityAction.Deny, Role = "asad")]
It would still allow me to invoke the method without throwing much of a fit
The question is, why?
My whole code:
static void Main(string[] args)
{
GenericIdentity identity = new GenericIdentity("JC", "Type1");
GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "Admin", "User" });
Thread.CurrentPrincipal = principal;
UsePrincipal();
}
static void UsePrincipal()
{
Console.WriteLine(Thread.CurrentPrincipal.Identity);
try
{
DevWork();
}
catch
{
Console.WriteLine("You Bad!");
}
Console.ReadKey();
}
[PrincipalPermission(SecurityAction.Deny, Role = "Admin")]
static void DevWork() // Will be executed no matter what the role is
{
Console.WriteLine("You Good!");
Console.ReadKey();
}
You can read in documentation of SecurityAction that Deny
is obsolete and:
In the .NET Framework 4, runtime support has been removed for enforcing the Deny, RequestMinimum, RequestOptional, and RequestRefuse permission requests. These requests should not be used in code that is based on .NET Framework 4 or later.
Since you are using .NET 4.5.2 - your Deny
request is simply being ignored.