如何解决使用Azure App Service身份验证的HttpContext用户为空
我在启用AAD身份验证的Azure应用服务上部署了.Net Core 3.1 Web API。
我正在尝试从Postman调用API,并且授权起作用,因为得到了响应。 不幸的是,当我尝试使用IHttpContextAccessor访问Http Context时,我看到该用户为空。
{
"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
}
}
跟随我的启动课程
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应用程序服务easy auth访问网络核心项目中的用户声明,我们需要使用带有请求标头的rread这些声明。有关更多详细信息,请参阅here
此外,您可以调用/.auth/me
端点并获取有关已认证用户的其他详细信息。您可以编写自定义中间件来检查X-MS-CLIENT-PRINCIPAL-ID
标头并调用/.auth/me
端点并手动设置用户声明。这是详细的代码示例,您可以参考类似的issue。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。