0
votes

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);
            }
        }
    }
}
1
AuthorizeAttribute doesn't seem to do it directly - see github.com/aspnet/Security/blob/master/src/… . More likely since the Roles property is inherited, that property is still being read by some other code in the framework which uses the data from the attribute to actually carry out the authorisation checks. I guess you could find the code somewhere in the source, I'm not personally sure where it would be off the top of my head. - ADyson
Thank you for the link, I'll be figuring it out then when I have the time. - Lukas

1 Answers

0
votes

When you inherit AuthorizeAttribute, you will naturally overwrite the IAuthorizeData interface. When the project starts, the attributes that implement the IAuthorizeData interface will be converted into the corresponding filter through AuthorizationApplicationModelProvider. About 2.x, he conversion process can be viewed in this code https://github.com/dotnet/aspnetcore/blob/2.1.3/src/Mvc/Mvc.Core/src/ApplicationModels/AuthorizationApplicationModelProvider.cs. Then, its authorization rules are passed to the filter.