Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Authorization Requirement Handler Using DI

I am trying to get a dependency injected into the constructor of a custom authorization handler, but the AddAuthorization in asp.net is making it difficult.

Handler:

class MyHandler : AuthorizationHandler<MyRequirement>
{
    readonly IDependent dependency;

    public UserExistsHandler(IDependent dependency)
    {
        this.dependency = dependency;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
    {
        context.Succeed(requirement);
    }
}

Program.cs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

builder.Services.AddSingleton<IAuthorizationHandler, MyHandler>();
builder.Services.AddAuthorization(config =>
{
    config.AddPolicy("MyPolicy", policy =>
    {
        // how?
        policy.AddRequirements(new )
    });
});

According to official documentation this should be possible:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/dependencyinjection?view=aspnetcore-6.0

However, the signature for AddRequirements is not generic and requires me to pass an actual instance of the handler which I cannot do because I have no reference to the IServiceProvider in the config delegate.

https://github.com/dotnet/aspnetcore/blob/4faa84c9ddf8c9e9cc9e5b43ca15f090037c4b68/src/Security/Authorization/Core/src/AuthorizationPolicyBuilder.cs#L73

How do I register the handler without having to create a new instance to be registered which defeats the purpose of the DI I am trying to do?

>Solution :

It’s not the handler that you need to pass to AddRequirements, but the an instance of MyRequirement.

builder.Services.AddAuthorization(config =>
{
    config.AddPolicy("MyPolicy", policy =>
    {
        policy.AddRequirements(new MyRequirement());
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading