Dependency Inject ClaimsPrincipal into DbContext when using EasyAuth in Azure Functions 2.0

azure azure-functions c# entity-framework-core

Question

Using Azure Functions 2.0 with EasyAuth (Azure one click option to enable authentication against azure ad).

This allows me to get given a ClaimsPrincipal in the function definition

public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, ClaimsPrincipal principal)

That's great but I'd love to be able to access the current userId in my DbContext so I can use the EFCore HasQueryFilter feature for security trimming.

My DbContext is injected into my azure function endpoint class, I'd prefer to keep it that way instead of manually creating it in the endpoint.

While I could probably set a property on my context each request, I would prefer to be able to inject the ClaimsPrincipal or parts of it into the DbContext via dependency injection so I don't need to do it manually in each function.

ClaimsPrincipal doesn't seem to be wired up for injection by default, nor have i figured out another class that I can inject that has access to it.

1
2
6/5/2019 2:41:33 AM

Accepted Answer

By registering IHttpContextAccessor for injection on startup

   public void Configure(IWebJobsBuilder builder)
   {
            builder.Services.AddHttpContextAccessor();
   }

You can then use that in the dbcontext

public DbContext(DbContextOptions<DbContext> options, IHttpContextAccessor httpContextAccessor) : base(options)
{
    if (httpContextAccessor != null)
    {
        var principal = httpContextAccessor.HttpContext.User;
        //do stuff here with principal
    }

}

4
6/5/2019 2:57:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow