Customizing Authorize attribute or Role based Authentication or Authorization in MVC
Previously I had shown how to....
DataTables in MVC:
- Code First Migrations in MVC 5
- Jquery DataTable in MVC
- Jquery DataTable multisearch paging and Sorting in MVC server side
- Jquery DataTable paging, Sorting and Multi search with datepicker in MVC server side
- Cascading DropDowns in Asp.Net MVC
- AngularJS with Web Api in Asp.net MVC using Token based Authentication
- Ajax helper Based Search in MVC
- Customizing Authorize attribute or Role based Authentication or Authorization in MVC
OutPut:
AngularJS:
public class CustomAuthorize : AuthorizeAttribute
{
private string RedirectReason = "RedirectReason";
public string Message { get; set; }
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
if (!filterContext.Controller.TempData.ContainsKey(RedirectReason))
filterContext.Controller.TempData.Add(RedirectReason, Message);
else
filterContext.Controller.TempData[RedirectReason] = Message;
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Home", action = "Index" }));
}
}
}
And now Add message in CustomAuthorize Attribute for Action Result as shown below.
[CustomAuthorize(Roles = "Admin", Message = "You do not have permission.")]
public ActionResult Index()
{
return View();
}
No comments:
Post a Comment