Azure Function: use parameter for SqlQuery from ClaimsPrincipal

103 Views Asked by At

I store ClaimsPrincipal inside FunctionContext.IInvocationFeatures list (inside auth middleware) and want to take a userId (key: ClaimTypes.NameIdentifier) as an argument to cosmosDb query. I can do it inside a function with this pseudo code:

 var allFeatures = ((HttpRequestData)req).FunctionContext.Features;
 var claimsPrincipalHolderFeature = allFeatures.First(..);
 var id = claimsPrincipalHolderFeature.Claims.First(c =>
     c.Type.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase)
 ).Value;
 // steps with CosmosClient

But I want to do it via CosmosDbInput attribute, something like:

public async Task<HttpResponseData> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "area")] HttpRequestData req,
    [CosmosDBInput(
        databaseName: "%CosmosDb%",
        containerName: "%CosmosContainer%",
        Connection = "CosmosDBConnection",
        SqlQuery = $"SELECT TOP 1 * FROM area a WHERE a.objectId = {{ClaimsPrincipal.Claims[{ClaimTypes.NameIdentifier}]}}")] List<Model> areas)

unfortunatelly this template{ClaimsPrincipal.Claims[{ClaimTypes.NameIdentifier}]} doesn't work, does anyone have any suggestions? If it's not possible and I need to implement custom bindings, it would be good to reuse some already existed code (CosmosDBInputAttribute and related code) and not create anything from scratch like for example described here

1

There are 1 best solutions below

0
On

Bindings can use Expressions coming from other Bindings, for example, you can use something from the HttpTrigger into the CosmosDBInput, but from the environment, I see no documentation stating that it's possible.

Values can be bound from:

  • App settings
  • Trigger file name
  • Trigger metadata
  • JSON payloads (for example what is coming from the HttpTrigger)
  • New GUID
  • Current date and time

Reference: https://learn.microsoft.com/azure/azure-functions/functions-bindings-expressions-patterns