Search code examples
asp.net-coreautofac

Add Authentication inside AutoFac ConfigureTenant


I would like to have Tenant Based Authentication on .NET Core App. I'm using AutoFac to build Tenant based Containers.

I was able to create a ServiceCollection and Populate the authentication services. However Authentication fails and getting Unauthorized response for the Tenant.

public static MultitenantContainer ConfigureMultitenantContainer(IContainer container)
{
    multitenantContainer.ConfigureTenant("80fdb3c0-5888-4295-bf40-ebee0e3cd8f3", containerBuilder =>
    {
        containerBuilder.RegisterType<DataService>().As<IDataService>().InstancePerDependency();
        containerBuilder.RegisterInstance(new OperationIdService()).SingleInstance();

        ServiceCollection tenantServices = new();
        tenantServices.AddAuthentication(opt =>
        {
            opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = "https://key-cloak.cloudapp.azure.com:8443/auth/realms/test";
            options.Audience = "test";
        });
        containerBuilder.Populate(tenantServices);
    });
    
    return multitenantContainer;
}

Solution

  • I was able to fix it myself with the help of this article.

    MultiTenant Authentication by Michael McKenna

    By default handlers aren’t registered using the default “.UseAuthentication” middleware. The schemes are registered in the middleware constructor before you have a valid tenant context. Since it doesn’t support registering schemes dynamically OOTB we will need to slightly modify it.

    We’re going to take the existing AuthenticationMiddleware.cs and just move the IAuthenticationSchemeProvider injection point from the constructor to the Invoke method. Since the invoke method is called after we’ve registered our tenant services it will have all the tenant specific authentication services available to it now.