I'm migrating my project to asp.net core and I'm stuck in migrating my CustomAuthorization attribute for my controllers. Here is my code.
public class CustomAuthorization : AuthorizeAttribute { public string Url { get; set; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery); } else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { filterContext.Result = new ViewResult { ViewName = "AcessDenied" }; } else { base.HandleUnauthorizedRequest(filterContext); } } }
then i used it to my controllers
[CustomAuthorization(Url = "/Admin/Account/Login", Roles = "Admin")] public abstract class AdminController : Controller { }
so, basically i can use it to redirect to different login page when roles is not met. I have few areas and each of them have different login page.