使用 Azure 应用服务身份验证的 HttpContext 用户为空

HttpContext User is empty with Azure App Service Authentication

我在启用 AAD 身份验证的 Azure 应用服务上部署了 .Net Core 3.1 Web API。

我正在尝试从 Postman 调用 API 并且授权有效,因为我收到了回复。 不幸的是,当我尝试使用 IHttpContextAccessor 访问 Http Context 时,我发现 User 是空的。

{
"Claims": [],
"Identities": [
    {
        "AuthenticationType": null,
        "IsAuthenticated": false,
        "Actor": null,
        "BootstrapContext": null,
        "Claims": [],
        "Label": null,
        "Name": null,
        "NameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
        "RoleClaimType": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
    }
],
"Identity": {
    "Name": null,
    "AuthenticationType": null,
    "IsAuthenticated": false
   }
}

这是我的 JWT 令牌包含的内容

关注我的创业公司class

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpContextAccessor();
        services.AddControllers();

        services.AddSwaggerGen();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "SDM API V1");
            c.RoutePrefix = string.Empty;
        });

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

这是我的控制器

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{       
    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IHttpContextAccessor httpContextAccessor;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IHttpContextAccessor httpContextAccessor)
    {
        _logger = logger;
        this.httpContextAccessor = httpContextAccessor;
    }

    [HttpGet]
    public string Get()
    {
        string jsonString = JsonSerializer.Serialize(httpContextAccessor.HttpContext.User);

        return "User: " + jsonString;
    }
}

我是不是漏掉了什么?

如果您想使用 Azure 应用服务轻松验证访问 net core 项目中的用户声明,我们需要使用 rread these claims with request headers。更多详情请参考here

此外,您可以调用 /.auth/me 端点并获取有关经过身份验证的用户的其他详细信息。您可以编写自定义中间件来检查 X-MS-CLIENT-PRINCIPAL-ID header 并调用 /.auth/me 端点并手动设置用户声明。下面是详细的代码示例,大家可以参考这个类似的issue.