кто-нибудь может объяснить следующее поведение 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 ().
Если я затем добавлю следующие строки:
new PrincipalPermission(null, "role1").Demand();
new PrincipalPermission(null, "roleX").Demand();
первый вызов по запросу проходит, но второй (как и ожидалось) вызывает SecurityException.
Почему вызов SecurityManager.IsGranted () не возвращает false для разрешения «roleX»?





Я считаю, что SecurityManager.IsGranted в основном рассматривает требования к коду (сборка и т. д.), А не конкретные требования, такие как основные разрешения.
Чтобы делать то, что вы хотите:
static bool HasAccess(string role)
{
IPrincipal principal = System.Threading.Thread.CurrentPrincipal;
return principal == null ? false : principal.IsInRole(role);
}
Из ответов на аналогичный вопрос здесь видно, что IsGranted () работает только с разрешениями CAS, а не с разрешениями, отличными от CAS.
Цитаты из статьи:
SecurityManager.IsGranted() determines whether a permission is granted by examining the CAS permissions that have been granted by the administrator. Since WorkingTimePermission is a non-CAS permission, that means the security policies set by the administrator have no impact regarding that permission. In other words, there is no way for an administrator to grant or revoke a [non-CAS permission]. Therefore SecurityManager.IsGranted() will always return false for [non-CAS permission].
и
It took me a while to get used to CAS vs. non-CAS permissions, and to realize that key phrases like "security policies" and "policy" only apply to CAS permissions. Once I got comfortable with that, deciphering apparently innocent help entries like SecurityManager.IsGranted's Remarks section became much easier:
"Granting of permissions is determined by policy..."
This implies - but doesn't explicitly state - that the method only works with CAS permissions, because it is checking the current security policy. It takes some getting used to.
В .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