Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How to override HandleUnauthorizedRequest in ASP.NET Core?

$
0
0

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.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>