Custom ASP.NET MVC Authorize Attribute

AuthorizeAttribute allows you to secure controller actions. The Authorize attribute lets you indicate that authorization is restricted to predefined roles or to individual users. This gives you a high degree of control over who is authorized to view any page on the site.

public class UserController : Controller
{
    [Authorize]
    public ActionResult Create()
    {
        return View();
    }

}

what this code do? If an unauthorized user tries to access create methods then If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.

public class UserController : Controller
{
    [Authorize(Roles = "Admin")]
    public ActionResult Create()
    {
        return View();
    }

}

Now the user who has admin role can only access to this methods. But what if i want to check this role from my user type enum?

[Serializable]
[Flags] //  When Enum mark with “Flags“ attribute it will work as bit field
public enum UserType
{
    Admin=1,
    PM= 2,
    Developer = 4
}

ok then lets write the custom Authorize Attribute.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
        public new UserType Roles;  // new keyword will hide base class Roles Property
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            IPrincipal user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
            {
                return false;
            }

            UserType role = (UserType)Lib.Models.User.CurrentUser.UserType; 
                                      // you could get User role or user type from session.

            if (Roles != 0 && ((Roles & role) != role))
            {
                 return false;
            }
            return true;
}

here i just override the AuthorizeCore methods of AuthorizeAttribute class. Now, you have to decorate your controller or action with this custom attribute and use bitwise operators to pass multiple roles.

[CustomAuthorize(Roles = UserType.Admin | UserType.PM)]
public ActionResult Create()
{
	return View();
}
Advertisements

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