Here is an attribute that I created that can be used to redirect to an unauthorized security action. it also allows you to specify the reason that will be transferred to the Unauthorized Action on the security controller, which can then be used for presentation.
You can create any number of properties to customize it to fit your specific application, just add it to your RouteValueDictionary document.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public sealed class ApplySecurityAttribute : ActionFilterAttribute { private readonly Permission _permission; public ApplySecurityAttribute(Permission permission) : this(permission, string.Empty) {} public ApplySecurityAttribute(Permission permission, string reason) { _permission = permission Reason = reason; } public string Reason { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!PermissionsManager.HasPermission(_permission))
Here is the security controller
public class SecurityController : Controller { public ViewResult Unauthorized(string reason) { var vm = new UnauthorizedViewModel { Reason = reason }; return View(vm); } }
Here is the attribute declaration on the controller you want to protect
[ApplySecurity(Permission.CanNuke, Reason = "You are not authorized to nuke!")]
This is how the PermissionsManager checks to see if the user has permissions.
public static class PermissionsManager { public static bool HasPermission(EZTracPermission permission) { return HttpContext.Current.GetCurrentUser().Can(permission); } }
source share