Finbuckle / Finbuckle.MultiTenant

Finbuckle.MultiTenant is an open-source multitenancy middleware library for .NET. It enables tenant resolution, per-tenant app behavior, and per-tenant data isolation.
https://www.finbuckle.com/multitenant
Apache License 2.0
1.26k stars 258 forks source link

Finbuckle With Identity Isolation Problem #583

Open onurkanbakirci opened 1 year ago

onurkanbakirci commented 1 year ago

I have an app which uses .net identity for membership system and Finbuckle for achieving multi-tenancy. I try to make .net identity TUser object as non multi-tenant and other things (TRole, TUserClaim etc. ) as multi-tenant. By the doc of Finbuckle, to achieve this purpose, i have to pass TUser class as a generic class and other things as default. So, my identity context class is as following,


public class IdentityContext : MultiTenantIdentityDbContext<AppUser>
    {
        public IdentityContext(ITenantInfo tenantInfo) : base(tenantInfo)
        {
        }

        public IdentityContext(ITenantInfo tenantInfo, DbContextOptions<IdentityContext> options) : base(tenantInfo, options)
        {
        }
        ....

So, everything is good so far. After these configurations i try to seed database with following code:

                //Set default tenant
                var accessor = scope.ServiceProvider.GetService<IMultiTenantContextAccessor>()!;
                var multiTenantContext = new MultiTenantContext<Tenant>();
                multiTenantContext.TenantInfo = defaultTenant;
                accessor.MultiTenantContext = multiTenantContext;

                var roleManager = scope.ServiceProvider.GetService<RoleManager<IdentityRole>>()!;

                if (!roleManager.Roles.Any())
                {
                    var role = new IdentityRole("SuperUser");
                    await roleManager.CreateAsync(role);

But in this point, RoleManager class of .net identity throws an error like following,

23502: null value in column "TenantId" of relation "AspNetRoles" violates not-null constraint

When i inspect to RoleManager props, i can see that the default tenant is set correctly under the Context class at runtime, but why .net identity throws this error?

AndrewTriesToCode commented 1 year ago

I'm sorry for the late reply. Do you have a sample project I can take a look at to see the issue closer? I have to admit I don't normally have a setup like this where user is not multi tenant and the others are.

One thing to try is setting TenantNotSetMode to Overwrite as described here. You would do that in the constructor of your context, the property should be inherited from MultiTenantIdentityDbContext<AppUser> for you to set.

stale[bot] commented 1 year ago

This issue has been automatically marked for closure because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.