Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I need to control the access to views based on users privilege levels (there are no roles, only privilege levels for CRUD operation levels assigned to users) in my MVC 4 application.

As an example; below the AuthorizeUser will be my custom attribute and I need to use it like this:

[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")]
public ActionResult UpdateInvoice(int invoiceId)
{
   // some code...
   return View();
}


[AuthorizeUser(AccessLevels="Create Invoice")]
public ActionResult CreateNewInvoice()
{
  // some code...
  return View();
}


[AuthorizeUser(AccessLevels="Delete Invoice")]
public ActionResult DeleteInvoice(int invoiceId)
{
  // some code...
  return View();
}

Is it possible to do it this way?

like image 475
chatura Avatar asked Oct 19 '22 21:10

chatura


People also ask

How can use Authorize attribute in ASP.NET MVC?

Here's how to use the Authorize attribute. You can apply the Authorize attribute to individual methods as well as the controller class as a whole. If you add the Authorize attribute to the controller class, then any action methods on the controller will be only available to authenticated users.

What is the use of AllowAnonymous in MVC 4?

The AllowAnonymous attribute in MVC is used to skip the authorization which is enforced by Authorization Filter in MVC. Now, run the application and navigate to /Home/NonSecured and you will see that it displays the page as expected and when you navigate to /Home/Secured, then it will redirect you to the Login page.

How to use authorization in MVC framework?

In the MVC framework there are filters that execute in sequence. The sequence is: It's clear that Authorization filters are taking care of authorizing the current user. If you are using the ASP.NET membership provider for authentication then it's quite easy to use Authorization in MVC. Here is an example. We can also specify Roles instead of Users.

What is [authorize] attribute in ASP NET?

ASP.Net’s [Authorize] attribute is another cool feature that makes it easy to add authentication at the Controller level when building a website, but the real goldmine here is that like nearly everything else in ASP.Net MVC, you can pick apart the functionality and extend it yourself – In...

What is the use of customauthorizeattribute?

It uses an identity form httpcontext and verifies/validates the user using the AuthorizeCore and OnAuthorization methods. Now I will put it into practice. I have created a simple CustomAuthorizeAttribute. A class is derived from the AuthorizeAttribute class (because we need the common behavior of Authentication).

How do I add a new role to a user?

Once logged in, we see the list of roles. We can also click Create to add a new role, as shown below: Now, we will create a new user with the “User” role. Next, we will log in as this user and click the “Role” link. The list of roles will be displayed (as the user role has access to the Index action).


2 Answers

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}
like image 251
chatura Avatar answered Oct 21 '22 10:10

chatura


Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }
like image 13
Leonid Minkov Avatar answered Oct 21 '22 11:10

Leonid Minkov