ASP.NET MVC: Custom Authorize Attribute
By Tan Lee Published on May 29, 2017 7.83K
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
- ASP.NET MVC Responsive Templates Free Download
- How to upload file in ASP.NET MVC
- How to Create Contact Form Flat Responsive in ASP.NET MVC
- How to check if HttpPostedFileBase is an image
- How to upload Multiple File in ASP.NET MVC
- ASP.NET MVC: Implement Password Reset with ASP NET Identity
- ASP.NET MVC: Getting Started
- ASP.NET MVC: Create Custom Routes
Categories
Popular Posts
Simple Responsive Login Page
Nov 11, 2024
Login SignUp form using HTML CSS JS
Nov 11, 2024
Material Lite Admin Template
Nov 14, 2024
Monster Admin Template
Nov 14, 2024