Sergii Zhuravskyi
Sergii Zhuravskyi

Reputation: 4348

Recommended way to retrieve ClaimsPrincipal in an isolated azure function(from HttpRequestData)

Environment: AzureFunction v4, Net 7, Isolated Function

is there a Microsoft recommended way of retrieving ClaimsPrincipal from HttpRequestData(https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.functions.worker.http.httprequestdata?view=azure-dotnet) ?

I have found the following two options

  1. Using mvc package with Azure Function: https://github.com/Azure/azure-functions-host/issues/4212#issuecomment-480378690 . I am talking about this package https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Abstractions.
  2. Implementing a custom solution like any of the following: 2.1 https://adamstorr.azurewebsites.net/blog/using-azure-functions-middleware-to-access-claimsprincipal-in-azure-static-web-apps 2.2 Developing Azure functions locally

It looks like using MVC package is the easiest option atm.

However, I don't see a comparison of the two approaches or recommendation what should be used. If you could list disadvantages/advantages of two approaches or provide a link to an article/documentation that looks into this problem that would have been great.

Upvotes: 2

Views: 2165

Answers (1)

Sergii Zhuravskyi
Sergii Zhuravskyi

Reputation: 4348

.Net 7 works exclusively using the isolated process for function apps and the Microsoft.Azure.Functions.Worker.Http library.

You cannot use Microsoft.AspNetCore.Mvc with .Net 7 function apps.

Even if you add Microsoft.AspNetCore.Mvc via a nuget (which you DO have to do with .Net 7 function app) and wire up your function to use HttpRequest it won't work, its just set to null on the function call... screenshot of .Net 7 function app using HttpRequest

You have acccess to the FunctionContext via the HttpRequestData object, but that still won't give you user claims like MVC HttpContext. If you want to extract them from the authorization header you'd have to write middleware to do so like the example here: https://adamstorr.azurewebsites.net/blog/using-azure-functions-middleware-to-access-claimsprincipal-in-azure-static-web-apps

You can specify ClaimsPrincipal as a function argument but it will be equal to null.

I haven’t personally tested the suggestion in the comment, but Arthuro Martinez mentions that it’s now feasible with the DarkLoop.Azure.Functions.Authorization.Isolated package. Please read his comment below and give it an upvote his comment if you find his suggestion valid

Upvotes: 4

Related Questions