基于角色的安全asp.net mvc试图传递一个方法
本文关键字:方法 一个 net 角色 于角色 安全 asp mvc | 更新日期: 2023-09-27 18:03:18
我想说清楚,我已经试过了,几乎可以成像了。
我的投篮有点像。
[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
我尝试这样做,因为我不认为每次我都必须更改控制器角色权限。。。。如果有人有想法,我们将不胜感激。
您可能可以使用自定义AuthorizeAttribute
执行类似的操作。这添加了一个步骤,在继续执行OnAuthorization
步骤之前设置Authorize属性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.
}
[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
}
希望这能帮助到别人。谢谢