Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Custom AuthorizeAttribute for controller utilizing parameter value?

I am trying to secure a controller action to prevent a user from accessing an Entity that they do not have access to. I am able to do this with the following code.

public ActionResult Entity(string entityCode)
{
    if (CurrentUser.VerifyEntityPermission(entityCode))
    {
        //populate viewModel...
        return View(viewModel);
    }
    return RedirectToAction("NoAccessToEntity", "Error");
}

I would like to be able to add an attribute to the controller action itself. In order to validate the access to the entity, I need to see what value has been passed to the controller and what entities the user has access to. Is this possible?

[EntityAuthRequired]
public ActionResult Entity(string entityCode)
{
        //populate viewModel...
        return View(viewModel);
}
like image 282
RSolberg Avatar asked May 12 '10 20:05

RSolberg


People also ask

How do I override an authorized attribute in .NET core?

Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.

How do you use AllowAnonymous?

[AllowAnonymous] bypasses all authorization statements. If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) are ignored.

Where can the Authorize attribute can be applied?

The Authorize attribute enables you to restrict access to resources based on roles. It is a declarative attribute that can be applied to a controller or an action method.


1 Answers

Something like this might help you on your way. Though you may want to add some additional properties to your attribute to allow you to specify your entityCode parameter on each action, rather than hard-code it.

public class EntityAuthRequired : FilterAttribute, IAuthorizationFilter 
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        //Make sure that this is not NULL before assigning value as string...
        var entityCode = filterContext.RouteData.Values["entityCode"] as string;
        // do your logic...         
        if (!allowed)
            filterContext.Result = new HttpUnauthorizedResult();            
    }
}

Also, if the entityCode isn't in your RouteData, you can use filterContext.RequestContext.HttpContext.Request to look at the POST data.

like image 150
Jab Avatar answered Oct 25 '22 18:10

Jab