php - How to lock down access between tenant users in a multi tenant laravel application

I am in the processed of building a multi tenant Laravel application where every tenant has their own database (which includes a users table).
The tenant is identified by the subdomain in the TenantServiceProvider and the the connection is changed to use the appropriate database when it figures out the tenant ID.
Everything is working as expected however I have come across a major security issue.
I log in to tenant1.mysite.com as user "John Doe" with ID 1
I change the url to tenant2.mysite.com and I am now logged in as "Jane Doe" who has an ID of 1 on the tenant2 site.
How can I prevent John Doe's session from being used on another tenant's site?
Answer
Solution:
One way to do it; in yourAuthenticate
middleware put a block such as;
When user logged-in successfully put the valuetenant1
in the user's session in a specified key.
Session::put('domain', 'tenant1');
in the same middleware even the authentication is correct, check whether the user's session match with the subdomain name. if they are matched then you proceed the user, else redirect him to login page.
Session::get('domain') === $this->getSubDomain($request)
public function getSubDomain(Request $request): string
{
$urlSegments = explode('.', parse_url($request->url(), PHP_URL_HOST));
return $urlSegments[0]; // this will return "tenant1"
}
Don't forget to removedomain
from session after user logged-out.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.