I'm using in my application, roles
and I'm trying to case, the user is not authorized, to be redirected to an error page.
I'm using ASP.NET MVC com Identity
, in internet search and here in 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 wrote down the HandleUnauthorizedRequest
method, thus:
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 Permissions of users in ASP.NET MVC 4
I also created a class, and sub-wrote the OnAuthorization
method, thus:
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 of the two funcina, when I try to access a page that is not authorized, I am redirected to the login screen.
My controller:
- Index - authenticated users only;
- About - Attended 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(); } }