I have created a custom authorization filter in ASP.NET Core 2.2 MVC in order to handle regular and AJAX requests, and to redirect to a custom URL if user is not authorized.
On some of my controller actions, I have the filter set [CustomAuthorize(Roles = "ExampleRole")]. Since I made a custom authorization filter, I thought I would need to also write the logic to check the role claims. However, CustomAuthorize filter is able to correctly handle roles without any additional code.
How is this happening? Is it the additional code inherited from AuthorizeAttribute class that continues to run after the custom OnAuthorization method runs?
Code for custom authorization filter:
public class CustomAuthorize : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
string redirectUrl = "/Auth/Login";
if (context.HttpContext.User.Identity.IsAuthenticated == false)
{
if (context.HttpContext.Request.IsAjaxRequest())
{
context.HttpContext.Response.StatusCode = 401;
//result is returned to AJAX call and user is redirected to sign in page
JsonResult jsonResult = new JsonResult(new { message = "Unauthorized", redirectUrl = redirectUrl });
context.Result = jsonResult;
}
else
{
context.Result = new RedirectResult(redirectUrl);
}
}
}
}