Custom MVC Role Authorize Attribute using App Settings

Here is a simple implementation of a custom [Authorize] attribute that uses appSettings get Role names:

The only important thing to note here is using Sytem.Web.Mvc, since the [Authorize] attribute also exists in System.Web.Http and has a slightly different implementation there.
I believe the two implementations have been unified in Asp.Net 5 / MVC 6, but that is still in preview.

using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyApp.Web.Attributes
{
    public class RoleAuthorizeAttribute : AuthorizeAttribute
    {

        public RoleAuthorizeAttribute(params string[] roleNames)
        {
            var roles = roleNames.Select(roleName => 
			ConfigHelper.GetAppSetting<string>(roleName)).ToList();

            this.Roles = string.Join(",", roles);
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return base.AuthorizeCore(httpContext);
        }
    }
}

Now you decorate your controllers / methods with [RoleAuthorize(“MyRoleName”)]

[RoleAuthorize("MyRoleName")]
public class MyController : Controller
{
	public ActionResult Index()
	{
		return View();
	}
}

And this is all for this post =)

Leave a Reply

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