基于角色的安全性asp.net mvc尝试传递方法

时间:2014-05-14 20:20:19

标签: c# asp.net security asp.net-mvc-4

我想要清楚,我几乎已经尝试过我可以成像。

我的拉斯拍摄就好像。

[Authorize()]
[Secure(Roles = ActionRole.Admin.ToString())]
public class ActionController : Controller
{
    public enum ActionRole
    {
        Admin,
        Recruter,
        Sales,
        Developer
    }
}

我最初的想法。

[Authorize()]
[Secure(Roles = MyRoleClass.GetAuthorizedRolesForThisAction("ActionController"))]
public class ActionController : Controller
{
    //ActionController Related Code.
}

public Class MyRoleClass(){

    Public strgin GetAuthorizedRolesForThisAction(string Controller){
        //Accessing my DB and the searching is not the hard part here.
    }

}

我收到此错误。

Error   1   An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type  

我试图这样做,因为不是我的想法,每次我必须更改控制器角色权限....如果任何人有想法,将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用自定义AuthorizeAttribute执行此类操作。这会添加一个步骤,在继续执行Roles步骤之前设置授权属性OnAuthorization

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class SecureAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext) {
        var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        this.Roles = string.Join(",", MyRoleClass.GetAuthorizedRolesForThisAction(controller));

        base.OnAuthorization(filterContext);
    }
}

然后您应该只需添加Secure属性修饰:

[Secure]
public class ActionController : Controller
{
    //ActionController Related Code.
}

答案 1 :(得分:0)

    [Authorize()]
    [Secure(Roles = "Contact/Index")]
    public ActionResult Index()
    {
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //Get the user permissions from the Session. 
        //Using it every time that I get the controller and the action
    }

希望这可能有助于某人。 感谢。