Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add AzureAD AND AzureADBearer to asp.net core 2.2 web 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));

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

like image 218
Chad Warren Stewart Avatar asked Apr 16 '19 00:04

Chad Warren Stewart


1 Answers

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));
like image 77
Chad Warren Stewart Avatar answered Nov 01 '22 14:11

Chad Warren Stewart