如何将AzureAD和AzureADBearer添加到ASP.NET Core 2.2 Web API [英] How to add AzureAD AND AzureADBearer to asp.net core 2.2 web api
问题描述
我正在尝试编写一个网站,该网站使用AzureAD对用户进行身份验证以访问UI来编写数据库中的项目.而且我还希望其他服务可以通过承载令牌来调用此API.
I'm trying to author a website that uses AzureAD to authenticate users to access UIs to author items in a DB. And I also want this API to be callable by other services via a bearer token.
services.AddAuthentication(o => {
o.DefaultScheme = AzureADDefaults.BearerAuthenticationScheme;
o.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
})
.AddAzureAD(options => Configuration.Bind("AzureAd", options))
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
我希望使用AzureAD方案对用户进行身份验证,但是对同一WEB API(在dif路由下)的服务要由承载者进行身份验证.或同时拥有所有路线.都可以
I want users to be authenticated using the AzureAD scheme, but services to the same WEB API (under a dif route) to be authenticated by the bearer. Or have all routes except both. Either works
推荐答案
最后通过创建一个策略方案来解决此问题,该策略方案根据存在的auth标头在两种模式之间切换:
ended up solving this by creating a policy scheme which toggles between the two schemas depending on the auth header present:
// add azure ad user and service authentication
services
.AddAuthentication("Azures")
.AddPolicyScheme("Azures", "Authorize AzureAd or AzureAdBearer", options =>
{
options.ForwardDefaultSelector = context =>
{
var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
if (authHeader?.StartsWith("Bearer") == true)
{
return AzureADDefaults.JwtBearerAuthenticationScheme;
}
return AzureADDefaults.AuthenticationScheme;
};
})
.AddAzureADBearer(options => config.Bind("AzureAdBearer", options))
.AddAzureAD(options => config.Bind("AzureAd", options));
这篇关于如何将AzureAD和AzureADBearer添加到ASP.NET Core 2.2 Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!