Show error page 404 after failure [Log in]

I have an action that I want to limit only the "Admin" role. I did it like this:

[Authorize(Roles = "Admin")] public ActionResult Edit(int id) 

After manually navigating the Controller / Edit / 1 path, I am redirected to the login page. Well, that is not bad, maybe, but I want to show 404 instead and try to use attributes for it. Is it possible?

+6
source share
2 answers

Is it possible?

Of course, you can write your own authorize attribute:

 public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/401.cshtml" }; } } 

and then use it:

 [MyAuthorize(Roles = "Admin")] public ActionResult Edit(int id) 

Note: you probably want to show page 401 or 403 if the user has not logged in instead of 404, which was not found for the file.

+14
source

In response to a comment by @Daniel about my comment on @Darin, this is my implementation:

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class CustomAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { string cookieName = FormsAuthentication.FormsCookieName; if (!filterContext.HttpContext.User.Identity.IsAuthenticated || filterContext.HttpContext.Request.Cookies == null || filterContext.HttpContext.Request.Cookies[cookieName] == null ) { HandleUnauthorizedRequest(filterContext); return; } var authCookie = filterContext.HttpContext.Request.Cookies[cookieName]; var authTicket = FormsAuthentication.Decrypt(authCookie.Value); string[] roles = authTicket.UserData.Split(','); var userIdentity = new GenericIdentity(authTicket.Name); var userPrincipal = new GenericPrincipal(userIdentity, roles); filterContext.HttpContext.User = userPrincipal; base.OnAuthorization(filterContext); } // Redirects unauthorized users to a "401 Unauthorized" page protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/Error/401.cshtml" }; } } 
+1
source

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


All Articles