HttpRequest.HttpContext.User (ClaimsPrincipal) object 在 Azure HttpTrigger 函数中不包含我的授权身份 Header

HttpRequest.HttpContext.User (ClaimsPrincipal) object in a Azure HttpTrigger Function does not contain my Identity from Authorization Header

[FunctionName("GetDetails")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/{Id}/details")] HttpRequest request, int Id)
{
    //my code here to get claims from the User context (request.HttpContext.User).
}

我还尝试在我的函数中注入 ClaimsPrincipal object,如下所示:

[FunctionName("GetDetails")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/{Id}/details")] HttpRequest request, int Id, **ClaimsPrincipal principal**)
{
    //my code here to get claims from the User context (request.HttpContext.User).
}

还是一样的结果。 为了在本地访问该功能,我传递了我的 Bearer 访问令牌,如下所示: 授权:不记名

知道我在这里遗漏了什么吗?

根据我的测试,使用request.HttpContext.User可以获得Azure portalAAD保护的函数的认证信息。

不明白你为什么要在本地传Bearer,如果你有这个需求,可以参考下面的代码:

            req.Headers.TryGetValue("Authorization", out var headers);

            var authorization = headers.First();

            var jwt = authorization.Split(' ')[1];
            var handler = new JwtSecurityTokenHandler();
            var token = handler.ReadJwtToken(jwt);
            var unique_name = token.Claims.First(claim => claim.Type == "unique_name").Value;
            log.LogInformation(unique_name);

可以参考Decode JWTs in C# for Authorization.

注:

如果遇到这个错误:

System.Private.CoreLib: Exception while executing function: Function1. FunctionPa: Could not load file or assembly 'System.IdentityModel.Tokens.Jwt, Version=6.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.

您可以在csproj文件中添加<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AzureFunctionsVersion>v3</AzureFunctionsVersion>
      <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>