Authentication HttpContext用户使用Azure应用程序服务身份验证为空
我在Azure应用程序服务上部署了一个.Net Core 3.1 Web API,在那里我启用了AAD身份验证。 我试图从Postman调用API,授权工作正常,因为我得到了响应。 不幸的是,当我尝试使用IHttpContextAccessor访问Http上下文时,我看到该用户是空的Authentication HttpContext用户使用Azure应用程序服务身份验证为空,authentication,azure-active-directory,asp.net-core-webapi,asp.net-core-3.1,httpcontext,Authentication,Azure Active Directory,Asp.net Core Webapi,Asp.net Core 3.1,Httpcontext,我在Azure应用程序服务上部署了一个.Net Core 3.1 Web API,在那里我启用了AAD身份验证。 我试图从Postman调用API,授权工作正常,因为我得到了响应。 不幸的是,当我尝试使用IHttpContextAccessor访问Http上下文时,我看到该用户是空的 { "Claims": [], "Identities": [ { "AuthenticationType": null,
{
"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令牌包含的内容
跟随我的创业班
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;
}
}
[ApiController]
[路线(“[控制器]”)]
公共类WeatherForecastController:ControllerBase
{
专用只读ILogger\u记录器;
专用只读IHttpContextAccessor httpContextAccessor;
公共天气预报控制器(ILogger记录器、IHttpContextAccessor httpContextAccessor)
{
_记录器=记录器;
this.httpContextAccessor=httpContextAccessor;
}
[HttpGet]
公共字符串Get()
{
字符串jsonString=JsonSerializer.Serialize(httpContextAccessor.HttpContext.User);
return“User:+jsonString;
}
}
我遗漏了什么吗?如果您想使用Azure应用程序服务easy auth访问net core项目中的用户声明,我们需要使用rread将这些声明与请求头一起使用。有关详细信息,请参阅 此外,您还可以调用
/.auth/me
端点并获取有关已验证用户的其他详细信息。您可以编写自定义中间件来检查X-MS-CLIENT-PRINCIPAL-ID
头并调用/.auth/me
端点并手动设置用户声明。下面是详细的代码示例,您可以参考类似的示例