Home > front end >  How do I get secrets.json or azure secrets in an Authorization filter?
How do I get secrets.json or azure secrets in an Authorization filter?

Time:08-29

I have secrets.json and Azure KeyVault setup in my application exactly as the MS tutorial suggest. I also have an authorization filter. All is working fine.

In a controller, I pass IConfiguration in and do:

_config["KEY"]

to access a value from my secrets.

How do I access these values in the custom AuthorizationFilter? It will not let me pass in attributes as I typically would.

In fact, if I could actually get my DbContext in the filter, I wouldn't need to access the config, but I can't pass that in either.

I want to either replace the string with a value from my vault or pull in the DbContext I created in Program.cs:

// Program.cs:
builder.Services.AddDbContext<DBContext>(options => Options.UseSqlServer(connectionString));

// In my filter...
public void OnAuthorization(AuthorizationFilterContext context)
{
    var optionsBuilder = new DbContextOptionsBuilder<DBContext>();
    optionsBuilder.UseSqlServer("{STRING}");
    var dbContext = new DBContext(optionsBuilder.Options);
    //...
}

CodePudding user response:

If I understand you correctly what you have to do would be to use httpContext services

 public class TestFilter : AuthorizeFilter
    {
        public override Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var config = context.HttpContext.RequestServices.GetService<IConfiguration>();
            var db = context.HttpContext.RequestServices.GetService<DBContext>();
            return base.OnAuthorizationAsync(context);
        }
    }

So you will use DI on Authorization request. I would assume that .net core would create singleton instance of filter this is why constructor injections wont work.

  • Related