Azure 函数:.NET Core:HTTP 触发器:Easy Auth:获取身份的对象 ID
Azure Function: .NET Core: HTTP Trigger: Easy Auth: Get object id of identity
我在 Windows 上使用 .NET Core 3.1 运行 有一个带 HTTP 触发器的 Azure 函数,启用了高级计划和简单验证。
如何检索发出请求的身份的对象 ID?
Windows 和 Linux 有两种工作方式:
- 通过请求 header
X-MS-CLIENT-PRINCIPAL-ID
- 通过 ClaimsPrincipal
示例:
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);
}
}
}
我在 Windows 上使用 .NET Core 3.1 运行 有一个带 HTTP 触发器的 Azure 函数,启用了高级计划和简单验证。
如何检索发出请求的身份的对象 ID?
Windows 和 Linux 有两种工作方式:
- 通过请求 header
X-MS-CLIENT-PRINCIPAL-ID
- 通过 ClaimsPrincipal
示例:
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);
}
}
}