Sunday, January 22, 2017

Customizing Authorize attribute or Role based Authentication or Authorization in MVC

As the TITLE says Customizing Authorize attribute, In this post I will show how to create a Customized Authorize attribute and use it. This is used to redirect the user to Home Page when he/she is authenticated and not authorized i.e, when the Authorize attribute generated 401 response it will redirect to Login page.
Previously I had shown how to...
DataTables in MVC:
AngularJS:
By creating a CustomAuthorize class which inherits AuthorizeAttribute we can redirect the user to home page instead of a login page.
How to use?
  

[CustomAuthorize(Roles = "Admin")]
public ActionResult Index()
{
 return View();
}


  

public class CustomAuthorize : AuthorizeAttribute
{
 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
 {
  if (!filterContext.HttpContext.Request.IsAuthenticated)
  {
   base.HandleUnauthorizedRequest(filterContext);
  }
  else
  {
   filterContext.Result = new RedirectToRouteResult(new
   RouteValueDictionary(new { controller = "Home", action = "Index" }));
  }
 }
}

No comments:

Post a Comment