aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Revisit TryAdd* vs Add* decision

Open jan-inimco opened this issue 8 years ago • 5 comments

Hi,

I want to add 2 JWT bearer authentication schemes to my authentication pipeline, one using azure B2C generated tokens and one using locally generated tokens.

If I add the 'b2cBearer' scheme BEFORE I add the 'localBearer' scheme I CAN use PostConfigure("jwtB2cBearer") to configure the JwtBearerOptions for the 'b2cBearer' scheme. The correct JwtBearerOptions instance is returned.

image

If I add the 'b2cBearer' scheme AFTER I add the 'localBearer' scheme I CANNOT use PostConfigure("jwtB2cBearer") to configure the JwtBearerOptions for the 'b2cBearer' scheme. An empty JwtBearerOptions instance is returned.

image

Why??

Can someone explain in detail what is going on? Is this related to IOC container behavior? One singleton being replaced by another?

Is there another way to get the JwtBearerOptions instance that is created within the 'AddAzureADB2CBearer' function call? Why isn't it simply a property member of 'AzureADB2COptions'??!

My sample code:

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authorization;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            var builder = services.AddAuthentication();

            builder.AddAzureADB2CBearer("b2cBearer", "jwtB2cBearer", options =>
            {
                Configuration.Bind("AzureAdB2C", options);
            });

            builder.AddJwtBearer("localBearer", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("MySymmetricSecurityKey")),

                    ValidateIssuer = true,
                    ValidIssuer ="MyIssuer",

                    ValidateAudience = true,
                    ValidAudience = "MyAudience",

                    ValidateLifetime = true,

                    ClockSkew = TimeSpan.Zero
                };

                options.SecurityTokenValidators.Clear();
                options.SecurityTokenValidators.Add(new SecurityTokenHandlerLocal());
            });

            services.PostConfigure<JwtBearerOptions>("jwtB2cBearer", options =>
            {
                options.SecurityTokenValidators.Clear();
                options.SecurityTokenValidators.Add(new SecurityTokenHandlerB2C());
            });

            services.AddAuthorization(options =>
            {
                var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder("localBearer", "b2cBearer");
                defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
                options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

jan-inimco avatar Nov 27 '18 08:11 jan-inimco

Looks like there is a bug on this line:

https://github.com/aspnet/AspNetCore/blob/master/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2CAuthenticationBuilderExtensions.cs#L64

And that it should always be an Add instead of a TryAdd.

And we also need to check if this problem exists in other AAD providers.

Eilon avatar Jan 10 '19 22:01 Eilon

In the meantime, as a workaround, just use the order that works for you.

Eilon avatar Jan 10 '19 22:01 Eilon

Sorry that I didn't post this sooner but I was waiting how long it would take for someone to explain what is going wrong...

The simplest fix is to not use the AddAzureADB2CBearer extension method from the Microsoft.AspNetCore.Authentication.AzureADB2C.UI nuget package so you can just pass along the desired options! Just add the JwtBearer directly and configure it yourself instead of letting the extension method do it for you:

            if (bool.Parse(configuration["Authentication:AzureAdB2C:IsEnabled"]))
            {
                var client = configuration["Authentication:AzureAdB2C:ClientId"];
                var instance = configuration["Authentication:AzureAdB2C:Instance"];
                var tenantDomain = configuration["Authentication:AzureAdB2C:Domain"];
                var signIn = configuration["Authentication:AzureAdB2C:SignUpSignInPolicyId"];

                authenticationBuilder.AddJwtBearer("azureAdBcBearer", options =>
                {
                    options.Authority = $"{instance}/{tenantDomain}/{signIn}/v2.0/";
                    options.Audience = client;
                });
            }

In my opinion the 'PostConfigure' stuff is an example of overly complex architectural design for the sake of adding architectural design instead of using architecture to simplify things. Almost no-one has a clue of what is going on internally... IOC spaghetti hell!!!

jan-inimco avatar Jan 11 '19 08:01 jan-inimco

@javiercn assigning to you to close when you merge your larger PR that contains the fix for this

HaoK avatar Feb 20 '19 17:02 HaoK

I don't think this has to be done in preview3, so feel free to move it out if your PR isn't gonna get in this week

HaoK avatar Feb 20 '19 17:02 HaoK