Search code examples
c#asp.net-core-2.2asp.net-authorization

Multiple AuthorizationHandlers vs. Single AuthorizationHandler with Switch/If Statements


I have successfully implemented the policy-based authorization in ASP.NET Core 2.2. I believe I understand the concept of how AuthorizationHandlers can perform requirement checks on an OR-basis.

But unless I'm missing something, couldn't the same OR-basis evaluation be accomplished within a single handler? Why not just use an if statement that says if this requirement has this property, do this; or if any of these conditions pass, requirement succeeds. Even the example on their page with the BuildingEntryRequirement seems like it could be also done via a single handler:

public class ExampleBuildingEntryHandler : AuthorizationHandler<BuildingEntryRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
        BuildingEntryRequirement requirement)
    {
        if (context.User.HasClaim(c => c.Type == "TemporaryBadgeId" && c.Issuer == "https://microsoftsecurity") ||
            context.User.HasClaim(c => c.Type == "BadgeId" && c.Issuer == "https://microsoftsecurity"))
        {
            // We'd also check the expiration date on the sticker.
            context.Succeed(requirement);
        }

        //TODO: Use the following if targeting a version of
        //.NET Framework older than 4.6:
        //      return Task.FromResult(0);
        return Task.CompletedTask;
    }
}

Is there a scenario I am missing that necessitates the use of multiple handlers?


Solution

  • If you are defining all the relevant implementation(s), no, you can do with a single handler.

    In fact, whatever is your requirement, you can develop one single custom handler that perfectly suits your needs.

    The samples are more interesting if you consider one could have completely distinct implementations of the authorization. Like:

    1. fully cookie based, via complex JWT token.
    2. database based, retrieves user data and checks for some condition.

    Now, it is true that you could do both in the same handler, but they don't really blend very well.

    So the ability of the framework to link more than one handler in this case would be handy, and allow for a better separation of concerns.