[SOLVED] Custom Authorize Attribute show denied message without routing to controller

Issue

In my ASP.NET web application, I’m using CustomAuthorizeAttribute for access control. So normal way is if the user role is not matched, the user will redirect to a controller and shows the access denied page.

Is there any way to do this like if the user role is not matched with authorization, Can’t it show the message or alert or something on the view without routing to the controller?

This is the Model.

public class RoleAuthorize: AuthorizeAttribute {
  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
      filterContext.Result = new HttpUnauthorizedResult();
    } else {
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
        controller = "Account", action = "AccessDenied"
      }));
    }
  }
}

Controller checking the authorization

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[RoleAuthorize(Roles = "1")]
public ActionResult DeleteConfirmed(int id) {
  M_Employee m_Employee = db.CreateEmployee.Find(id);
  db.CreateEmployee.Remove(m_Employee);
  db.SaveChanges();
  return RedirectToAction("Index");
}

Editing

I tried doing this

 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
   if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
     filterContext.Result = new HttpUnauthorizedResult();
   } else {
     System.Web.HttpContext.Current.Session["error"] = "You're not authorize for this action";
     
   }
 }

And the page I have modified as

< div class = "form-actions no-color" > @HttpContext.Current.Session["error"] < input type = "submit"
value = "Delete"
class = "btn btn-default" / > | @Html.ActionLink("Back to List", "Index") < /div>

But it not working.

Solution

You can try this.

 public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
    
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }           
            else
            {
                filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");
                filterContext.Result = new RedirectResult("~/Error");
            }
        }

Answered By – Moiez Hussain

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *