ASP.NET MVC 5 handles unauthorized access request
I am trying to implement an access denied error page in a new ASP.NET MVC 5 project with individual user account authentication mode. I am adding a class CustomAuthorize
that inherits fromAuthorizeAttribute
public class CustomAuthorize : AuthorizeAttribute
{
protected virtual CustomPrincipal CurrentUser
{
get { return HttpContext.Current.User as CustomPrincipal; }
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
if (!string.IsNullOrEmpty(Roles))
{
if (!CurrentUser.IsInRole(Roles))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
//base.OnAuthorization(filterContext); // returns to login url
}
}
if (!string.IsNullOrEmpty(Users))
{
if (!Users.Contains(CurrentUser.UserName))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
//base.OnAuthorization(filterContext); // returns to login url
}
}
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
}
}
}
add ErrorController.cs
public class ErrorController : Controller
{
public ActionResult AccessDenied()
{
return View();
}
}
and AccessDenied.cshtml
viewing
<h2>Access Denied</h2>
<p>You do not have access to view this page</p>
then applied in HomeController.cs
[CustomAuthorize]
public class HomeController : Controller
but it always redirects to the login page. How to display the access denied page?
source to share
Create a new mvc 5 project with separate user accounts, add your Error Controller, view and CustomAuthorize attribute class.
Then update your home controller as shown below.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[CustomAuthorize(Roles = "TestRole")]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
Register and log into the system, try to click the "About" link, you will be redirected to a page with denied access, since there is no user with the "TestRole"
source to share