a developer's notes – a semi-technical web development BLOG

August 15, 2013

ASP.NET MVC 4 Custom Authorize Attribute

Filed under: ASP.NET MVC — Duy Nguyen @ 4:58 pm
Tags: , , , , ,

When you need to add a custom authorize attribute, create a new class (in the web layer of your application or in a location that has the HttpContextBase reference).

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("", MethodToGetUserRights(httpContext.User.Identity.Name.ToString())); // MethodToGetUserRights needs defined

        if (privilegeLevels.Contains(this.AccessLevel))
        {
            return true;
        }
        else
        {
            return false;
        }            
    }
}

You can then decorate your action methods like this…

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...

    return View();
}

If you rather use enums instead of strings you can. Just change the custom property to an enum type.

//...
// Custom property
    public MyAccessEnum AccessLevel { get; set; }
//...

Then in your action method, use the enum for the AccessLevel value.

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

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: