如何将AzureAD和AzureADBearer添加到asp.net core 2.2 web api

问题描述 投票:1回答:2

我正在尝试创建一个网站,该网站使用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路径下)提供服务。或者除两者外都有所有路线。要么有效

c# authentication asp.net-core azure-active-directory asp.net-core-webapi
2个回答
0
投票

您可以将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" };
}

0
投票

最终通过创建一个策略方案来解决这个问题,该方案根据当前的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));
© www.soinside.com 2019 - 2024. All rights reserved.