0
I am using in my application, roles
and I am trying if, user is not authorized, is redirected to an error page.
I’m using ASP.NET MVC com Identity
, in research on the Internet and here at Stackoverflow, I found some answers, but none of them worked:
ASP.NET - Redirect to Error Page if Roles Authorization Fails
In this case, I created a class, and I sub-wrote the method HandleUnauthorizedRequest
, being like this:
public class PermissoesFiltro : System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// The user is not authenticated
base.HandleUnauthorizedRequest(filterContext);
}
else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
{
// The user is not in any of the listed roles =>
// show the unauthorized view
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/Page_403.cshtml"
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
In this other example: Authentication and User Permissions in ASP.NET MVC 4
I also created a class, and I sub-wrote the method OnAuthorization
, being like this:
public class PermissoesFiltro : System.Web.Mvc.AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if(filterContext.Result is HttpUnauthorizedResult)
{
filterContext.HttpContext.Response.Redirect("~/Views/Shared/Page_403.cshtml");
}
}
}
But neither, when I try to access a page that is not authorized, I am redirected to the login screen.
My controller:
- Index - only authenticated users;
- About - attentive users who belong to the rule "TEST";
Contact - All.
public class HomeController : Controller { [Authorize] public ActionResult Index() { return View(); } [Authorize(Roles = "TESTE")] public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } }
How’s the controller signature? Enter the code for us to see, please?
– Ricardo
I made a review thank you.
– Thomas Erich Pimentel
Because you are not using [Permissions] instead of [Authorize]. You have created the attribute but are not using
– user26552
@Murilo did not understand, so I wanted to use the
roles
but directing to a specific page.– Thomas Erich Pimentel