How to provide base classes for authorization requirements?

318 Views Asked by At

I've got a few authorization requirement types that are very similar. The first type takes a string[] of roles to check the user's role against. The second type takes a string[] of elevated roles that can short-circuit the handler and another string[] of checked roles like the first. Let's say I then have the following:

public abstract class RoleRequirement : IAuthorizationRequirement
{
    internal string[] CheckedRoles { get; }

    public RoleRequirement(string[] checkedRoles)
    {
        CheckedRoles = checkedRoles;
    }
}

public abstract class ElevatedRoleRequirement : RoleRequirement
{
    internal string[] ElevatedRoles { get; }

    public ElevatedRoleRequirement(string[] elevatedRoles, string[] checkedRoles) 
    : base(checkedRoles)
    {
        ElevatedRoles = elevatedRoles;
    }
}

I have a few concrete variations of both types and the associated handlers accept those concrete types. The issue is DI is resolving them all as a base RoleRequirement even though the actual type passed to the handler is a concrete type. This causes the wrong handler to be invoked which can't deal with the given type.

I've tried registering the handlers as both singletons and scoped without benefit though I'll most likely need scoped handlers. Each look like the following:

 services.AddSingleton<IAuthorizationHandler, SomeRoleRequirementHandler>();
 services.AddSingleton<IAuthorizationHandler, SomeElevatedRoleRequirementHandler>();

Is it possible to design this in a way to keep this DRY?

0

There are 0 best solutions below