Search code examples
c#asp.net-coreauthenticationrazor-pagesasp.net-roles

make AuthorizationHandler accept two resources instead of one


I have completed this tutorial on authorization in asp.net razorpages.

I have multiple models and would love to allow the Adminhandler to have access to all of the models. The tutorial is structured in a way which uses the C# interface called AuthorizationHandler.

By nature it only accepts one resource. I am not a master in C#. So what I did is i copied the code of the AuthorizationHandler class to implement my own class which accepts multiple resources.

This what i have thus far. I admit that I am not sharpest nail in the toolbox and am now stuck as what to code into the HandleAsync and HandleRequirementAsync bodies. Please forgive me if my question sounds silly but I am experienced yet in creating custom interfaces.

using System.Diagnostics; using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Authorization {

public abstract class AuthorizationHandler<TRequirement, T1, T2> : IAuthorizationHandler where TRequirement : IAuthorizationRequirement
{
    protected AuthorizationHandler();

  
    [DebuggerStepThrough]
    public virtual Task HandleAsync(AuthorizationHandlerContext context);
    

    protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, T1 first, T2 second);
}

}


Solution

  • I have multiple models and would love to allow the Adminhandler to have access to all of the models. The tutorial is structured in a way which uses the C# interface called AuthorizationHandler.

    This has been implemented in AuthorizationHandler , just implement the HandleAsync method, you can get all requirements you add from AuthorizationHandlerContext.

    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        var requirements = context.PendingRequirements.ToList();
    
        return Task.CompletedTask;
    }
    

    For more details, refer to the doc: Use a handler for multiple requirements