ASP.NET MVC: Custom Authorize Attribute

By FoxLearn 5/29/2017 7:23:19 PM   7.47K
How to Custom authorize attribute with ASP.NET Identity MVC 5 using C#, Entity Framework Code First

Step 1: Open Shared folder, then create a AuthorizeFailed view as below

@{
    ViewBag.Title = "Authorize Failed";
}

<h2>AuthorizeFailed</h2>
<p>@ViewData["Message"]</p>

Step 2: Create a CustomAuthorizeAttribute class, then add code as below

[AttributeUsage(AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string ViewName { get; set; }

    public CustomAuthorizeAttribute()
    {
        ViewName = "AuthorizeFailed";
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        IsUserAuthorized(filterContext);
    }

    void IsUserAuthorized(AuthorizationContext filterContext)
    {
        //user is authorized
        if (filterContext.Result == null)
            return;
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            ViewDataDictionary dic = new ViewDataDictionary();
            dic.Add("Message", "You don't have sufficient privileges for this operation !");
            var result = new ViewResult() { ViewName = this.ViewName, ViewData = dic };
            filterContext.Result = result;
        }
    }
}

Step 3: Open HomeController, then change code as below

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [CustomAuthorize(Roles = "Admin")]//user 1
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }

    [CustomAuthorize(Roles = "Sales")]//user 2
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

VIDEO TUTORIALS