我正在尝试创建一个网站,该网站使用AzureAD对用户进行身份验证,以访问用户界面以创建数据库中的项目。我还希望这个API可以通过承载令牌由其他服务调用。
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路径下)提供服务。或者除两者外都有所有路线。要么有效
您可以将AddAzureADBearer
中间件添加到您的应用程序:
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
sharedOptions.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
})
.AddAzureAD(options => Configuration.Bind("AzureAd", options))
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
假设你的应用程序中有api控制器,如果另一个应用程序将访问受AAD保护的web api,你应该设置架构:
[HttpGet]
[Authorize(AuthenticationSchemes = "AzureADBearer")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
最终通过创建一个策略方案来解决这个问题,该方案根据当前的auth头在两个模式之间切换:
// 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));