Search code examples
asp.net-coreauthorizationwebapi

Invoke AuthorizationHandler in .NET Core


In an ASP.NET Core 6 Web API, I'm trying to invoke an AuthorizationHandler function. I want to create an authorization mechanism that first will authenticate the user from AWS cognito with [Authorize] tag - this part is working.

After that, I want my own custom authorization mechanism.

My problem is that the AuthorizationHandler function is not invoked.

This are the parts from my code:

Program.cs

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ScreenAuthorizationPolicy", policy =>
    {
        policy.Requirements.Add(new ScreenAuthorizationRequirement());
    });
});
builder.Services.AddSingleton<IAuthorizationHandler, ScreenAuthorizationHandler>();
.
.
app.UseAuthentication();
app.UseAuthorization();


app.MapControllers();
app.UseCors("*");
app.Run();

AuthorizationAttribute.cs

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
    public class ScreenAuthorizationAttribute : Attribute
    {
        public Screens ScreenID { get; }
        public PermissionLevel PermissionLevel { get; }

        public ScreenAuthorizationAttribute(Screens screenID, PermissionLevel permissionLevel)
        {
            ScreenID = screenID;
            PermissionLevel = permissionLevel;
        }
    }

ScreenAuthorizationRequirement.cs

public class ScreenAuthorizationRequirement : IAuthorizationRequirement
    {
    }

ScreenAuthorizationHandler.cs

public class ScreenAuthorizationHandler : AuthorizationHandler<ScreenAuthorizationRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        ScreenAuthorizationRequirement requirement)
    {
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

This is the function I need to get into.

In my controller I'm writing

 [Route("api/[controller]/Endpoint")]
 [Authorize]
 [ScreenAuthorization(Screens.screen1, PermissionLevel.Read)]
 public async Task<IActionResult> GetSomething()

Thanks for the help


Solution

  • You may confuse the usage of the two authorization policies.

    The first one: Policy-based authorization

    use a requirement, a requirement handler, and a preconfigured policy.

    Apply policies to controllers by using the [Authorize] attribute with the policy name. For example:

    [Authorize(Policy = "AtLeast21")]
    public class AtLeast21Controller : Controller
    {
        public IActionResult Index() => View();
    }
    

    The second one: Custom Authorization attributes

    deriving from AuthorizeAttribute, and use a custom IAuthorizationPolicyProvider to control how authorization policies are supplied.

    You can apply it to actions in the same way as other Authorize attributes.For example:

    [MinimumAgeAuthorize(10)]
    public IActionResult RequiresMinimumAge10()