using System.Web.Mvc; using System.Security; namespace Website.Security { /// /// Role filter for protecting resources by Role. /// /// /// Gratuitously copied, pasted, and modified from Fredrik Norman's blog post: /// http://weblogs.asp.net/fredriknormen/archive/2008/03/12/asp-net-mvc-framework-2-interception-and-creating-a-role-action-filter.aspx /// public class RoleFilterAttribute : ActionFilterAttribute { private readonly IRoleProvider roleProvider; public string Roles { get; set; } public RoleFilterAttribute() { roleProvider = GlobalApplication.Container.Resolve(); } public RoleFilterAttribute(IRoleProvider roleProvider) { this.roleProvider = roleProvider; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var username = filterContext.HttpContext.User.Identity.Name; var userRoles = roleProvider.GetRolesForUser(username); foreach (var definedRole in Roles.Split(',')) { foreach (var role in userRoles) { if (definedRole.Equals(role)) return; } } throw new SecurityException("Access not granted!"); } } }