Search code examples
authenticationazure-active-directoryasp.net-core-webapiasp.net-core-3.1httpcontext

HttpContext User is empty with Azure App Service Authentication


I have a .Net Core 3.1 Web API deployed on an Azure App Service where I enabled AAD Authentication. enter image description here

I am trying to call the API from Postman and the Authorization works, because I get a response. Unfortunately, when I try to access Http Context with a IHttpContextAccessor, I see that User is empty.

{
"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
   }
}

This is what my JWT token contains enter image description here

Follows my Startup 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();
        });
    }
}

And this is my Controller

[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;
    }
}

Did I miss something?


Solution

  • if you want to access user claims in net core project with Azure app service easy auth, we need to use rread these claims with request headers. For more details, please refer to here enter image description here

    Besides, you could invoke the /.auth/me endpoint and obtain additional details on the authenticated user. You could write your custom middleware to check the X-MS-CLIENT-PRINCIPAL-ID header and invoke the /.auth/me endpoint and set the user claims manually. Here is the detailed code sample, you could refer to this similar issue.