2014-05-14 73 views
0

我想說清楚,我已經嘗試幾乎可以成像。基於角色的安全性asp.net mvc試圖通過一個方法

我的拉斯維加斯槍是類似的東西。

[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 

我試圖做到這一點,因爲是不是我的主意,每一個,我要改變控制器角色權限....如果任何人有一個想法的時候,將不勝感激。

+0

安全的自定義屬性?它是什麼樣子的? –

回答

1

你可以用自定義的AuthorizeAttribute做這樣的事情。這添加了一個步驟,在繼續執行OnAuthorization步驟之前設置授權屬性Roles

[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. 
} 
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 
    } 

希望這可以幫助別人。 謝謝。