views:

354

answers:

3

Hi,

can anybody please explain the following c# behaviour? I have written a small console application just to learn about CAS, but I can not seem to understand why the following lines of code work like they do:

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")));

The output is "true" for both SecurityManager.IsGranted() calls.

If I then add the following lines:

 new PrincipalPermission(null, "role1").Demand();
 new PrincipalPermission(null, "roleX").Demand();

the first demand call passes, but the second one (as expected) causes a SecurityException.

Why does not the SecurityManager.IsGranted()-call return false for the "roleX" permission?

A: 

I believe SecurityManager.IsGranted is mainly looking at code demands (the assembly etc) - not specific demands such as principal permissions.

To do what you want:

    static bool HasAccess(string role)
    {
        IPrincipal principal = System.Threading.Thread.CurrentPrincipal;
        return principal == null ? false : principal.IsInRole(role);
    }
Marc Gravell
A: 

Thank you for your answer,

yes, I know that would be a way of "avoiding" using the SecurityManager class. But I am still a bit frustrated since I was expecting the outcome of the two methods (.IsGranted() vs .Demand()) to be the same.

+1  A: 

From the answers to a similar question here it appears that IsGranted() only works with CAS permissions, and not non-CAS permissions.

Quotes from article:

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].

and

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.

Robert Paulson