我的代码看起来像这样:
[PrincipalPermission(SecurityAction.Demand, Role = "RoleA")]
class Foo
{
[PrincipalPermission(SecurityAction.Demand, Role = "RoleB")]
public static bool Bar()
{
return true;
}
}
如果我尝试运行Foo.Bar();
如果我没有角色 A,它将失败,但从不检查角色 B。无论我是否有角色 B,只要我有角色 A,它都可以工作。
如果我从类定义中删除[PrincipalPermission(SecurityAction.Demand, Role = "RoleA")]
,那么它会按预期检查 RoleB。
我四处搜索,发现在两个不同的 SO 问题(这里和这里(上提到了这个确切的问题,但这两种情况都没有答案。一个评论指向一个旧的Microsoft连接链接,据称其中包含答案,但没有评论或答案实际说明问题是什么。
我真的非常感谢对此的任何帮助。
多个 PrincipalPermissionAttribute 需求使用 OR 组合,因此在您的情况下:
- RoleA 可以构造类的实例并调用任何方法。
- RoleB 可以调用方法 Bar,但不能调用构造函数。
因此,您的代码等效于:
[PrincipalPermission(SecurityAction.Demand, Role = "RoleA")]
class Foo
{
[PrincipalPermission(SecurityAction.Demand, Role = "RoleA")]
public Foo()
{
}
[PrincipalPermission(SecurityAction.Demand, Role = "RoleA")]
[PrincipalPermission(SecurityAction.Demand, Role = "RoleB")]
public static bool Bar()
{
return true;
}
}
如果要使用 AND 组合需求,则应将 Role= 指定为逗号分隔的列表,例如"角色 A,角色 B"。 或者适当地使用 SecurityAction.Deny 。
下面的示例对此进行了说明:
class Program
{
static void Main(string[] args)
{
var aPrincipal = new GenericPrincipal(new GenericIdentity("AUser", ""), new[] {"RoleA"});
var bPrincipal = new GenericPrincipal(new GenericIdentity("BUser", ""), new[] { "RoleB" });
var abPrincipal = new GenericPrincipal(new GenericIdentity("ABUser", ""), new[] { "RoleB", "RoleA" });
// AB can do anything
Thread.CurrentPrincipal = abPrincipal;
var sc = new SecureClass();
TryConstruct();
TryBMethod(sc);
TryABMethod(sc);
// What can A do?
Thread.CurrentPrincipal = aPrincipal;
TryConstruct();
TryBMethod(sc);
TryABMethod(sc);
// What can B do?
Thread.CurrentPrincipal = bPrincipal;
TryConstruct();
TryBMethod(sc);
TryABMethod(sc);
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
}
static void TryConstruct()
{
try
{
var sc = new SecureClass();
}
catch(SecurityException)
{
Console.WriteLine("Constructor SecurityException for " + Thread.CurrentPrincipal.Identity.Name);
}
}
static void TryBMethod(SecureClass sc)
{
try
{
sc.RoleBMethod();
}
catch (SecurityException)
{
Console.WriteLine("RoleBMethod SecurityException for " + Thread.CurrentPrincipal.Identity.Name);
}
}
static void TryABMethod(SecureClass sc)
{
try
{
sc.RoleABMethod();
}
catch (SecurityException)
{
Console.WriteLine("RoleABMethod SecurityException for " + Thread.CurrentPrincipal.Identity.Name);
}
}
}
[PrincipalPermission(SecurityAction.Demand, Role ="RoleA")]
class SecureClass
{
public SecureClass()
{
Console.WriteLine("In constructor using " + Thread.CurrentPrincipal.Identity.Name);
}
[PrincipalPermission(SecurityAction.Demand, Role = "RoleB")]
public void RoleBMethod()
{
Console.WriteLine("In RoleBMethod using " + Thread.CurrentPrincipal.Identity.Name);
}
[PrincipalPermission(SecurityAction.Demand, Role = "RoleA,RoleB")]
public void RoleABMethod()
{
Console.WriteLine("In RoleBMethod using " + Thread.CurrentPrincipal.Identity.Name);
}
}