I have an Azure Function with HTTP Trigger using .NET Core 3.1 running on Windows with Premium Plan and Easy Auth enabled.
How can I retrieve the Object Id of the identity making the request?
CodePudding user response:
There two ways that work for Windows as well as Linux:
- Via the request header
X-MS-CLIENT-PRINCIPAL-ID
- Via the ClaimsPrincipal
Example:
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log,
ClaimsPrincipal claimsPrincipal)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string objectIdHeaders = req.Headers["X-MS-CLIENT-PRINCIPAL-ID"];
log.LogInformation($"Headers: {objectIdHeaders}");
string objectIdClaims = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
log.LogInformation($"Headers: {objectIdClaims}");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
}