Securing a security descriptor in ASP.NET MVC with AspNetSqlRoleProvider

I am looking to protect various areas of my MVC application to prevent a standard user from accessing views like admin. Currently, if a user is registered and they try to view the About page (from a window template in visual studio), he simply redirects them to the login page. I would prefer the user to be informed that they do not have permission to view the page.

[Authorize(Roles="Admin")] public ActionResult About() { return View(); } 

It seems redundant to send an already verified user to the login page when they don’t have permission.

+4
source share
1 answer

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)) // Put security check here { var routeValueDictionary = new RouteValueDictionary { { "controller", "Security" }, // Security Controller { "action", "Unauthorized" }, // Unauthorized Action { "reason", Reason } // Put the reason here }; filterContext.Result = new RedirectToRouteResult(routeValueDictionary); } base.OnActionExecuting(filterContext); } } 

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); } } 
+3
source

Source: https://habr.com/ru/post/1299681/


All Articles