aspnetcore 3.1 dependency injection for filter

Viewed 166

I have a filter inside my netcore 3.1 application:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class JwtAuthenticationAttribute : Attribute, IAuthorizationFilter
    {
        // Custom property
        public string Permission { get; set; } = "";

        private readonly AppSettings _appSettings;

        public JwtAuthenticationAttribute(IOptions<AppSettings> appSettings) : base()
        {
            _appSettings = appSettings.Value;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            throw new NotImplementedException();
        }

 }

And I had to implement Dependency Injection because I need to get the IOptions into my constructor.

On my Startup.cs I just had to do this:

  services.AddScoped<JwtAuthenticationAttribute>();

And then add the following attribute to my API method:

[ServiceFilter(typeof(JwtAuthenticationAttribute))]

This is all working, but if you see in detail, my Filter has a custom parameter that I need to pass, and based on the above attribute I can't pass it.

How can I pass an attribute to it so I still get access to my Injected Depencency and also the parameter.

Before DI, I was using:

 [JwtAuthentication(Permission = "Security.User.Update")]

But the above way can't let me get dependency injection.

Any clue?

1 Answers

Because of the nature of how this attribute is to be used, the service locator anti-pattern will have to be used via the current context

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class JwtAuthenticationAttribute : Attribute, IAuthorizationFilter {
    // Custom property
    public string Permission { get; set; } = "";

    public void OnAuthorization(AuthorizationFilterContext context) {
        IServiceProvider services = context.HttpContext.RequestServices;

        AppSettings appSettings = services.GetService<IOptions<AppSettings>>().Value;

        //...
    }
}
Related