Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

 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.

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.

How do i parse the value USR_SAVE and process custom authentication using CustomAuthorizeFilter?

like image 330
Billa Avatar asked Jul 07 '13 06:07

Billa


2 Answers

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!

like image 187
Murali Murugesan Avatar answered Oct 06 '22 15:10

Murali Murugesan


You can use a filter attribute:

public class ACLCheckAttribute : FilterAttribute, IActionFilter

In OnActionExecuting, you can grab 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
  • Session, etc.: HttpContext would also have these.
  • 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

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.

like image 25
Brian Mains Avatar answered Oct 06 '22 14:10

Brian Mains