aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

AzureADB2CBearer scheme and JwtBearer scheme

Open jan-inimco opened this issue 8 years ago • 14 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

Looking at the code it already configures JwtBearer, so you only need to align the scheme and place the logic in the PostConfigure.

https://github.com/aspnet/AADIntegration/blob/master/src/Microsoft.AspNetCore.Authentication.AzureADB2C.UI/AzureAdB2CAuthenticationBuilderExtensions.cs#L49

dcarr42 avatar Nov 27 '18 11:11 dcarr42

Looking at the code it already configures JwtBearer, so you only need to align the scheme and place the logic in the PostConfigure.

https://github.com/aspnet/AADIntegration/blob/master/src/Microsoft.AspNetCore.Authentication.AzureADB2C.UI/AzureAdB2CAuthenticationBuilderExtensions.cs#L49

Thank you for the reply. But I think I do exactly what you say, no?

If I add the 'b2cBearer' scheme BEFORE I add the 'localBearer' scheme then in the PostConfigure delegate the JwtBearerOptions.TokenValidationParameters.ValidAudience property IS set correctly (as expected because info is passed via AzureADB2COptions).

If I add the 'b2cBearer' scheme AFTER I add the 'localBearer' scheme then in the PostConfigure delegate the JwtBearerOptions.TokenValidationParameters.ValidAudience IS NOT set correctly (it is null although info was passed via AzureADB2COptions).

I don't understand why...

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

Try using JwtBearerOptionsConfiguration

dcarr42 avatar Nov 27 '18 12:11 dcarr42

Try using JwtBearerOptionsConfiguration

I'd love to but the class is internal

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

Ha. Didn't notice. This is slightly awry. 🙄

dcarr42 avatar Nov 27 '18 12:11 dcarr42

You can use IConfigureNamedOptions, but register it as an IConfigureOptions

services.AddSingleton<IConfigureOptions<JwtBearerOptions>,YourClassConfigureOptions>();

dcarr42 avatar Nov 27 '18 13:11 dcarr42

Just check ordering around the call to AddAzureADB2CBearer

dcarr42 avatar Nov 27 '18 13:11 dcarr42

Looking deeper I think depending on which bearer auth is successful will depend on whether the post config will flow. Hence the ordering maybe a side effect of this.

https://github.com/aspnet/HttpAbstractions/blob/master/src/Microsoft.AspNetCore.Authentication.Core/AuthenticationService.cs#L63

dcarr42 avatar Nov 27 '18 20:11 dcarr42

@javiercn - do you have any thoughts on this issue?

Eilon avatar Dec 06 '18 22:12 Eilon

@javiercn - any thoughts on this?

Eilon avatar Dec 13 '18 22:12 Eilon

@mkArtakMSFT who's the owner of this area now?

muratg avatar Jan 31 '19 22:01 muratg

@muratg still me

javiercn avatar Feb 01 '19 07:02 javiercn

Found the issue:

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

This should be TryAddEnumerable

javiercn avatar Feb 01 '19 08:02 javiercn

This is also addressed by https://github.com/aspnet/AspNetCore/pull/7096

javiercn avatar Feb 23 '19 08:02 javiercn