当类上有 PrincipalPermission 时,方法上的 PrincipalPermission 将被忽略 [英] PrincipalPermission on methods is being ignored when there is PrincipalPermission on class

查看:35
本文介绍了当类上有 PrincipalPermission 时,方法上的 PrincipalPermission 将被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解一直是方法上的安全属性将覆盖类上的安全属性,但似乎不再是这种情况,如下面的简单代码所示:

My understanding has always been that security attributes on methods will override security attributes on class, but that doesn't seem to be the case any more as the simple code below demonstrates:

class Program
{
    [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] //<-- this passes
    class DumbClass
    {
        [PrincipalPermission(SecurityAction.Demand, Role = "ffff")] //<-- this passes (but shouldn't)
        public string EchoMethod(string input)
        {
            return input;
        }
    }

    static void Main(string[] args)
    {
        Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity("manual"));

        //this should throw becuase the principal is not in the role "ffff"
        //BUT DOESN'T
        Console.WriteLine(new DumbClass().EchoMethod("this"));
    }
}

如果我删除类上的声明,则会得到预期的安全异常.我是否错过了一些非常明显的东西.我正在使用 .Net 4.5

If I remove the declaration on the class then I get the expected security exception. Am I missing something really obvious. I'm using .Net 4.5

推荐答案

因为 PrincipalPermissionAttribute 需求是使用 OR 组合的,一个类属性本质上和给每个方法添加属性是一样的,你的例子相当于:

Because PrincipalPermissionAttribute Demands are combined using OR, and a class attribute is essentially the same as adding the attribute to each method, your example is equivalent to:

[PrincipalPermission(SecurityAction.Demand, Authenticated = true)] 
class DumbClass
{
    [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] 
    public DumbClass()
    {
    }

    [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] 
    [PrincipalPermission(SecurityAction.Demand, Role = "ffff")]
    public string EchoMethod(string input)
    {
        return input;
    }
}

并且由于 OR 逻辑,您对 Role="ffff" 的需求是多余的.

and because of OR logic, your demand for Role="ffff" is redundant.

如果您想将 EchoMethod 限制为角色ffff",并允许经过身份验证的用户使用所有其他方法,请将您的代码更改为:

If you want to restrict EchoMethod to role "ffff", and allow authenticated users for all other methods, change your code to:

class DumbClass
{
    [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] 
    public DumbClass()
    {
    }

    [PrincipalPermission(SecurityAction.Demand, Role = "ffff")]
    public string EchoMethod(string input)
    {
        return input;
    }

    [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] 
    public string OtherMethod(string input)
    {
        return input;
    }

}

这篇关于当类上有 PrincipalPermission 时,方法上的 PrincipalPermission 将被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆