TAGS :Viewed: 5 - Published at: a few seconds ago

[ Store tenant id in the asp.net session? ]

I am building a multi tenant MVC4 web application. I distinguish the tenant based on the url alias (customername.webapp.net). I have a database that stores the customer id which I can lookup using the customername.

Obviously I need this customer identification during the entire session that a user from that customer is using my webapp.

Is it acceptable to store this unique identifier in the session? Or are there better design choices for this kind of "session data"?

Answer 1


I'd rather store this information inside the UserData portion of the forms authentication cookie (if you are using Forms Authenticatoin) or simply add it as a claim if you are using claims based authentication. When the user logs-in you would extract the tenant name from the current request, query your database in order to obtain the tenant id and then persist this id. If you store the id in the UserData portion of the Forms Authentication cookie you could write a custom [Authorize] attribute which will read the FormsAuthenticationTicket, decrypt it, get the tenant id from the UserData portion and then build a custom principal. This way you will have it available everywhere in your application. If you use claims based authentication, you would simply add it as a new claim.

I wouldn't use Session at all inside my application.

Answer 2


Please don't be misguided by the answer. It is dangerous to use cookie.

Session in this case would be the valid option, not cookies. If you store your tenantId inside your cookie, and your application establishes database connection based on your cookie, then after you login as a user, you can tamper and change the cookie and now your application will make connection to another database thereby compromising security. Even if your cookie is encrypted, it's not 100% reliable.

Session in this case would be the reliable server information that keeps track of which tenant database should be connected to. Although session can be a performance drop compared to cookie, in this case you have no other good options. You are designing a multitenancy application and that's just something you have to sacrifice.

Yes, you may still able to use cookie if you REALLY want to. You just have to keep checking if the user is connected to the right database somehow, which to me is more of a performance drop than using session.

Don't hate session just because alot of people abuse it or hate it. You just have to use it in the right manner.

Bottom line is, if you are using any info for security purposes, don't use cookie.