Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

[AbpSession] set TenantId in anonymous sessions #1306


User avatar
0
daws created

Hello there !

i'm moving my architecture to an database per tenant approach. My app will have connected users and public (anonymous) users.

my main app could be accessed by logged user (full function) or anonymous user (restricted function) but both of them use data specific from each tenant.

So, I need that an anonymous user which retrieve the index.cshtml from HomeController have the tenantId to retrieve WebAPI requests from the correct database.

Based on the {TENANCY_NAME}.mydomain.com (or other full url); i could know which tenant is requested in my homeController. Is it possible to have the tenantId set somewhere for the anonymous user ?

I could include the tenant Id manually in each request to WebAPI, but it seems not efficient at all since it's already implemented in ABP based on the user session.

my HomeController is like this right now :

[AbpMvcAuthorize]
public ActionResult Index()
{
	return View(AbpSession.TenantId != null ? "~/App/Main/views/index.cshtml" : "~/App/Dashboard/common/views/layout/layout.cshtml");

I would like to go somewhere like this :

[AllowAnonymous]
public ActionResult Index()
{
	if (AbpSession == null)
	{
		//set the session to anonymous user with specific tenant Id based on subdomain
	}
   return View(AbpSession.TenantId != null ? "~/App/Main/views/index.cshtml" : "~/App/Dashboard/common/views/layout/layout.cshtml");

Thanks for your help !


1 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Check how we got the TenantId in IAbpSession.TenantId: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp/Runtime/Session/ClaimsAbpSession.cs#L50">https://github.com/aspnetboilerplate/as ... ion.cs#L50</a>

    You can try this:

    1. Create a new YourAbpSession class derived from IdentityFrameworkClaimsAbpSession (<a class="postlink" href="https://github.com/aspnetboilerplate/module-zero/blob/dev/src/Abp.Zero/Runtime/Session/IdentityFrameworkClaimsAbpSession.cs">https://github.com/aspnetboilerplate/mo ... Session.cs</a> inherits ClaimsAbpSession)

    2. Override TenantId and get it from somewhere else, for example from an HTTP header. And send this header in every request to the server. If you can not find header, return base.TenantId.

    You can make (2) also using cookies, which may be better and works for non-ajax requests also. Just set cookie when session begins (in global.asax for example) and check it in your session.