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.33k stars 265 forks source link

Programmatically change tenant #335

Closed szymczakk closed 4 years ago

szymczakk commented 4 years ago

Hi,

Is there a way to change the tenant from the code? I have a HostStrategy registered in my code, but I have to create a user for a different tenant that I'm currently on. (I have an admin tenant that create new tenants, and I have to provide the first user for that tenant) Is there a way to do that?

I'm using ASP NET Core 3.1 with MVC, API and Razor Pages, with Finbuckle.MultiTenant 6.0.0

Thanks, Krzysiek

natelaff commented 4 years ago

So, you want to briefly impersonate another tenant essentially?

Unless I'm misunderstanding you, you could probably create a new strategy and register it as well, and just create that user with some way to trigger that.

For instance, create a strategy to read the tenant from an http header or something, have it registered first, then host strategy second. When you create the user, add the tenant it needs to go to into the request header and that should essentially work? Not sure about how secure that would be, so you'd want to think through that a little bit, but an approach like this would probably work.

AndrewTriesToCode commented 4 years ago

@szymczakk There is an HttpContext extension method called TrySetTenantInfo which will let you set the tenant for the rest of the request. I also will clear out any DI resolution/caching that already occurred for the prior tenant if you want it to.

If you don't have access to HttopContext you can get IMultiTenantContextAccessor<T> from DI (where T is your tenant info type) and if you set the tenant info on that instance it is effectively the same result -- future requests for tenant will get the new value. This method doesn't clear out any DI options resolved for the prior tenant so you should be more careful with it.

I hope that helps, let me know if you have any more questions.

szymczakk commented 4 years ago

@AndrewTriesToCode I forgot about TrySetTenantInfo. Thanks for that, I will try to do it like this.

szymczakk commented 4 years ago

@natelaff This sounds like a complex but a very clever solution. I like that ;) If TrySetTenantInfo provided by @AndrewTriesToCode not works I will try it like that 😉

szymczakk commented 4 years ago

TrySetTenantInfo works great for me.

Closing it, thanks @AndrewTriesToCode 😉