ASP.Net MVC: Simple Custom Authorization by Inheriting from the AuthorizeAttribute

Implementing custom authorization to a ASP.Net MVC site can be quite simple if you take advantage of the built-in ActionFilter authorization framework. Here’s how to do it.

First, this enumeration describing four levels of access to the site.

// They types of user we have on the site
public enum UserRole
	Guest = 0,
	User = 1,
	SuperUser = 2,
	Admin = 4

Here’s a quick and dirty example of a session based reference to the current user that will be used to verify that he or she has access to the controller action requested.

// The custom session object that keeps 
// track of the current user
public static class MySessionObject
	public static User Current 
		get { return (User)HttpContext.Current.Session["CurrentUser"];  } 
		set { HttpContext.Current.Session["CurrentUser"] = value;  } 
	public static bool MemberHasAtLeastRole(UserRole matchTo)
		return Current.Roles.Any(testRole => (int)testRole >= (int)matchTo);

This is what does the real “work”. By inheriting from the built-in AuthorizeAttribute, you take advantage of ASP.Net MVC’s built-in authorization framework. Just override the Roles property with your own UserRole class and check that your current user has “at least” that role in the AuthorizeCore method override.

// The custom authorization attribute
public class CustomAuthorizeAttribute : AuthorizeAttribute
	public new UserRole Roles; // Notice the "new"
	protected override bool AuthorizeCore(HttpContextBase httpContext)
		// Generally authenticated to the site
		if (!httpContext.User.Identity.IsAuthenticated)
			return false;
		//Next, specific roles this user has
		if (Roles != 0)
			return MySessionObject.MemberHasAtLeastRole(Roles);
		return true;

And finally, in your controller, you apply the attribute to the applicable controller actions. Or, if every controller action requires the same level of authorization, you could apply it to the class declaration of the controller.

public class MyController : Controller
	[CustomAuthorize(Roles = UserRole.SuperUser)]
	public ActionResult MyControllerAction()
		return View();

Hope this helps!

This entry was posted in ASP.Net, Attributes, C#, MVC. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *