0

I created a custom Authorization attribute and I want to use a service in it but I'm not sure how to use it there as dependency injection doesn't work well.

public class MyAuthorizationAttribute : Attribute, IAuthorizationFilter
{
    public static Func<IMyService> MyService { get; set; }

    public MyAuthorizationAttribute()
    {
        Console.WriteLine("Attribute Initialized");
    }

    public async void OnAuthorization(AuthorizationFilterContext context)
    {
        await MyService.Validate(...);

        Console.WriteLine("OnAuthorization");
    }
}

Trying with a delegate function but no success as well (MyService is always null), any ideas? And is the correct use of this?

I would like to use this attribute like this :

[HttpGet]
[MyAuthorizationAttribute]
[Route(...)]
public async Task<ActionResult> GetMyMethodAsync()
{
    //...
} 

I just want to avoid to use the same code in every endpoint.

This is how the service is registered :

builder.Services.AddScoped<Func<IMediator>>(x => x.GetRequiredService<IMediator>);
user7849697
  • 503
  • 1
  • 8
  • 19
  • Passing a service via the constructor is not allowed for an attribute. – user7849697 Jul 01 '23 at 18:55
  • And you probably don't want to make it a static property, to avoid concurrency issues for one. – Xerillio Jul 01 '23 at 18:56
  • Ah, you're right, I had my head somewhere else. What are you trying to achieve with it? How about using a [custom policy](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-7.0#custom-iauthorizationpolicyprovider) instead? You should be able to inject into that as usual – Xerillio Jul 01 '23 at 19:04
  • I check every API call the 'claims' linked to the user based on the token. This code I want to place behind a custom attribute. – user7849697 Jul 01 '23 at 19:08
  • My question is how to use a service via a func delegate and is this the right way to use a attribute tag. – user7849697 Jul 01 '23 at 19:10
  • Dependency injection into attributes doesn't seem like a good idea - [see this answer](https://stackoverflow.com/a/29916075/3034273). I'd recommend looking into [claims based policies](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-7.0#adding-claims-checks) - you can also make a policy the default policy so the standard `[Authorize]` attribute uses this unless otherwise specified – Xerillio Jul 01 '23 at 19:16

0 Answers0