How to add AzureAD AND AzureADBearer to asp.net core 2.2 web api

梦想的初衷 提交于 2019-12-10 21:51:35

问题


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));

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


回答1:


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));



回答2:


You can add the AddAzureADBearer middleware to your application :

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
    sharedOptions.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
})
.AddAzureAD(options => Configuration.Bind("AzureAd", options))
.AddAzureADBearer(options => Configuration.Bind("AzureAdBearer", options));

Suppose you have api controller in your application , if another application will access the web api which protected by AAD , you should set the schema :

[HttpGet]
[Authorize(AuthenticationSchemes = "AzureADBearer")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}


来源:https://stackoverflow.com/questions/55698938/how-to-add-azuread-and-azureadbearer-to-asp-net-core-2-2-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!