Tag Archives: Custom Attributes

Custom Role Attributes in ASP.NET MVC

Here is the code for defining and applying custom Role attributes in ASP.NET MVC. This specific example checks to see if the user is part of a given Active Directory group, but changing this to a custom validation should be fairly obvious.

Code in the controller:

[MyAuthorizeAttribute(Roles = “{AD group goes here}”)]
//ActionMethod code goes here…

Code to implement the attribute:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyProject.Controllers
{
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.User.Identity.IsAuthenticated)
{
UserGroups groups = new MyProject.Shared.ActiveDirectory.UserGroups(HttpContext.Current.User.Identity.Name);
var roles = ( Roles ?? string.Empty).Split(‘|’);

//if granted role exist in users group or if its admin-overload ( admin permission) for all menu
if (groups.IsInDistGroup(Roles) )
{
return true;
}
}
return base.AuthorizeCore(httpContext);
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new ViewResult
{
ViewName = “~/Views/Shared/NotValid.cshtml”
};
}
}
}