Azure HttpTrigger 函数中的 HttpRequest.HttpContext.User (ClaimsPrincipal) 对象不包含来自授权标头的我的身份

问题描述

[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 对象,如下所示:

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

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

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

解决方法

根据我的测试,使用request.HttpContext.User可以获取AADAzure portal保护的函数的鉴权信息。

我不明白你为什么在本地传递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.

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

<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>