有人能解释一下下面的c#行为吗?我写了一个小的控制台应用程序,只是为了了解CAS,但我似乎不能理解为什么下面这几行代码会这样工作:
string[] myRoles = new string[] { "role1", "role2", "role3" };
GenericIdentity myIdentity = new GenericIdentity("myUsername", "customAuthType");
GenericPrincipal myPrincipal = new GenericPrincipal(myIdentity, myRoles);
System.Threading.Thread.CurrentPrincipal = myPrincipal;
Console.WriteLine(SecurityManager.IsGranted(new PrincipalPermission(null, "role1")));
Console.WriteLine(SecurityManager.IsGranted(new PrincipalPermission(null, "roleX")));对于两个SecurityManager.IsGranted()调用,输出都是"true“。
如果我添加了以下几行:
new PrincipalPermission(null, "role1").Demand();
new PrincipalPermission(null, "roleX").Demand();第一个demand调用通过,但第二个调用(如预期的那样)会导致SecurityException。
为什么SecurityManager.IsGranted()-call没有为"roleX“权限返回false?
发布于 2013-06-13 16:11:04
在.NET 4.0中,SecurityManager.IsGranted已被废弃。
这就是它曾经的样子,如果你在.NET 4.0兼容性下编译,它会报错。
bool isGranted = SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.Infrastructure))要修复它,请执行以下操作:
var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
bool isGranted = permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);参考资料:
http://www.stringbuilder.net/post/2009/07/31/In-NET-40-SecurityManagerIsGranted-is-obsolete.aspx
发布于 2008-11-26 00:37:40
从对类似问题here的回答中可以看出,IsGranted()只适用于CAS权限,而不适用于非CAS权限。
引用自文章:
CAS SecurityManager.IsGranted()通过检查管理员已授予的
权限来确定是否授予权限。由于WorkingTimePermission是非归档存储权限,这意味着管理员设置的安全策略对该权限没有影响。换句话说,管理员无法授予或撤销非CAS权限。因此,对于非归档存储权限,SecurityManager.IsGranted()总是返回false。
和
我花了一段时间才习惯于CAS和非CAS权限,并意识到像“安全策略”和“策略”这样的关键短语只适用于CAS权限。一旦我对此感到满意,破译SecurityManager.IsGranted的备注部分等明显无害的帮助条目就变得容易得多:
“权限的授予由策略决定...”
这意味着-但没有明确声明-该方法只适用于CAS权限,因为它正在检查当前的安全策略。这需要一些时间来适应。
发布于 2008-11-23 13:15:38
我相信SecurityManager.IsGranted主要关注代码需求(程序集等),而不是像主体权限这样的特定需求。
做你想做的事:
static bool HasAccess(string role)
{
IPrincipal principal = System.Threading.Thread.CurrentPrincipal;
return principal == null ? false : principal.IsInRole(role);
}https://stackoverflow.com/questions/311677
复制相似问题