简体   繁体   English

自定义“授权过滤器”属性参数

[英]Customize Authorize Filter attribute parameter

I have the following requirement to implement the Access Control list 我有以下要求来实现访问控制列表

public class SecurityObject{
public string Key{get;set;}
public string DisplayName{get;set;}
public bool isAllowed{get;set;}
}

public class Role{
List<SecurityObject> AccessibleObjects{get;set;}
}

Currently I use forms authentication for basic authorization. 目前,我使用表单身份验证进行基本授权。 Below is my code 下面是我的代码

Global.asax.cs Global.asax.cs

 public class MvcApplication : System.Web.HttpApplication
 {
    public override void Init()
    {
        this.PostAuthenticateRequest += new 
                           EventHandler(MvcApplication_PostAuthenticateRequest);

        base.Init();
    }
    void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
      HttpCookie authCookie =
       HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            string encTicket = authCookie.Value;
            if (!String.IsNullOrEmpty(encTicket))
            {
                FormsAuthenticationTicket ticket = 
                                 FormsAuthentication.Decrypt(encTicket);

                string[] userData = ticket.UserData.Split(new string[] { "___" },
                                 StringSplitOptions.None);
                string[] roles = null;
                if (userData.Length > 1)
                {
                    roles = userData[1].Split(',');
                }
            MyCustomIdentity identity = new MyCustomIdentity(ticket);
            GenericPrincipal principle = new GenericPrincipal(identity, roles);
            HttpContext.Current.User = principle;
            }
        }
    }}

My current controller class 我当前的控制器类

public class AdminController : Controller
 {
  [HttpPost, Authorize, ValidateAntiForgeryToken]
    public ActionResult SaveUser(UserDetailViewModel viewModel)
    {

    }
  }

My Target controller class 我的目标控制器类

public class AdminController : Controller
 {
  [HttpPost, Authorize(ACLKey="USR_SAVE"), ValidateAntiForgeryToken]
    public ActionResult SaveUser(UserDetailViewModel viewModel)
    {

    }
  }

I want my action method to be decorated with ACLKey and I would like to check whether the User Role has the given key and based on that I need to execute or return HttpUnauthorizedResult page, even for Ajax requests from jQuery. 我希望用ACLKey装饰我的操作方法,并且我想检查用户角色是否具有给定的键,并以此为基础,即使对于来自jQuery的Ajax请求,我也需要执行或返回HttpUnauthorizedResult页面。

I referred many like Customizing authorization in ASP.NET MVC But i didnt find a way to execute both forms authentication and my custom ACLKey check. 我提到了很多类似ASP.NET MVC中的“自定义授权”,但是我没有找到一种执行表单身份验证和自定义ACLKey检查的方法。

How do i parse the value USR_SAVE and process custom authentication using CustomAuthorizeFilter? 如何解析值USR_SAVE并使用 CustomAuthorizeFilter 处理自定义身份验证

You can try like this 你可以这样尝试

public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
    public string AllowFeature { get; set; }

    public void OnAuthorization(AuthorizationContext filterContext)
    {

        var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true)
                                .Where(a => a.GetType() == 
                               typeof(FeatureAuthenticationAttribute));
        if (filterAttribute != null)
        {
            foreach (FeatureAuthenticationAttribute attr in filterAttribute)
            {
                AllowFeature = attr.AllowFeature;
            }
       List<Role> roles = 
       ((User)filterContext.HttpContext.Session["CurrentUser"]).Roles;
       bool allowed = SecurityHelper.IsAccessible(AllowFeature, roles);
         if (!allowed)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}

In you action method 在你的行动方法

    [FeatureAuthentication(AllowFeature="USR_SAVE")]
    public ActionResult Index()
    {
    }

Hope this will help you! 希望能帮到你!

You can use a filter attribute: 您可以使用过滤器属性:

public class ACLCheckAttribute : FilterAttribute, IActionFilter

In OnActionExecuting, you can grab USR_SAVE. 在OnActionExecuting中,您可以获取USR_SAVE。 Without knowing where it comes from, I would assume that it comes from: 不知道它来自哪里,我会假设它来自:

  • The Form: you can grab any form values from the context passed into ONActionExecuting, by navigating to the HttpContext.Request.Form collection 表单:您可以通过导航到HttpContext.Request.Form集合,从传递到ONActionExecuting的上下文中获取任何表单值。
  • Session, etc.: HttpContext would also have these. 会话等:HttpContext也将具有这些。
  • The action method: From an attribute, using the context passed in for the action, it has a list of ActionParameters that can be accessed like a dictionary, allowing you to check and extract your value 动作方法:从属性中,使用为动作传入的上下文,它具有一个ActionParameters列表,可以像字典一样进行访问,从而允许您检查和提取值

If somewhere else, please comment where. 如果还有其他地方,请在哪里评论。 You can apply this attribute to a controller or method, or globally set it by adding it to the globalfilters collection (GlobalFilters.Filters.Add()), or in the FilterConfig file in the App_Start folder. 您可以将此属性应用于控制器或方法,也可以通过将其添加到globalfilters集合(GlobalFilters.Filters.Add()),或在App_Start文件夹的FilterConfig文件中进行全局设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM