Quick Summary: Learn how to implement secure multi-tenant authentication in CodeIgniter 4, from tenant identification and membership verification to session management and route protection. This guide also covers tenant-level data isolation, organisation switching, and security testing to help prevent unauthorised access.
A bookkeeper at a small accounting firm signs in to a SaaS invoicing platform. She manages the books for two client companies and has a seat in her own firm’s workspace. One email address, one password, three organisations. The login succeeds, but a more important question comes straight after it: which organisation’s invoices is she allowed to see right now?
This is where CodeIgniter 4 authentication needs more than a standard login form. CodeIgniter gives you sessions, filters, validation, and a query layer. It does not ship a tenant-aware system, and even if you build on an official package such as CodeIgniter Shield, tenant membership stays your own application logic. This article follows the request lifecycle to show where that logic belongs.
1. The First Security Decision: Which Tenant Is This User Logging Into?
Before checking a password, the application should know which organisation the request is for. There are three common sources of that context:
- Tenant subdomains, such as northwind.yourapp.com.
- Custom organisation domains, such as billing.northwind.com, mapped to a tenant record.
- A tenant identifier on the user account, which suits apps where each user belongs to exactly one organisation.
Whichever you choose, resolve it on the server against records you control. Look up the requested host in your tenants table and treat a miss as a 404. In Config\App, the $allowedHostnames setting can further restrict which hostnames the framework accepts. Never trust a tenant_id hidden field or request header as fact, because the browser controls it.
The resolved tenant is only a claim about where the user wants to go. It becomes access once membership is verified, as the next section shows. For how tenants and databases are modelled, our guide to multi-tenant SaaS on Laravel and React covers the architecture side. This article stays on authentication.
2. Designing the Login Flow Around Tenant Membership
Take Priya, who works for Northwind Foods and also consults for Harbor Logistics, whose membership was suspended last month. She has one valid account and two very different outcomes. A multi-tenant CodeIgniter login should reflect that:
- Resolve the tenant from the host.
- Validate the submitted credentials and look up the user.
- Verify the password with PHP’s password_verify() against the stored hash.
- Look for a membership row linking this user to this tenant.
- Confirm that membership is active.
- Only then regenerate the session and store the user and active tenant.
Invalid credentials should produce one generic message, whether the email is unknown or the password is wrong, so the form does not reveal which accounts exist. A failed membership check should be a separate, deliberate outcome. Priya’s credentials are correct at Harbor Logistics, so an “invalid password” message would be misleading. A clear denial that logs the attempt is better.
The key rule is that a valid account does not imply membership. The session should not exist until every check above has passed, which makes step six the last line of the flow rather than the first.
3. Using CodeIgniter 4 Filters to Protect Tenant-Specific Routes
Filters are the natural home for per-request enforcement. A filter implements CodeIgniter\Filters\FilterInterface, with before() and after() methods, and is registered under an alias in app/Config/Filters.php:
php
public array $aliases = [
'tenant' => \App\Filters\TenantAccess::class,
];
A filter that combines authentication, tenant resolution, and membership checks looks like this:
php
namespace App\Filters;
use App\Models\MembershipModel;
use App\Models\TenantModel;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class TenantAccess implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$userId = session()->get('user_id');
if (! $userId) {
return redirect()->to('/login');
}
$tenant = (new TenantModel())->findByHost($request->getUri()->getHost());
if ($tenant === null) {
return service('response')->setStatusCode(404);
}
$membership = (new MembershipModel())
->where('user_id', $userId)
->where('tenant_id', $tenant['id'])
->where('status', 'active')
->first();
if ($membership === null) {
return service('response')->setStatusCode(403);
}
service('tenantContext')->set($tenant, $membership);
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
}
}
You then apply it to a route group:
php
$routes->group('app', ['filter' => 'tenant'], static function ($routes) {
$routes->get('invoices/(:num)', 'Invoices::show/$1');
});
CodeIgniter supplies the filter mechanism and the route grouping. Everything else is yours: findByHost() and the tenantContext service are custom code, and the membership schema is your design. Since filter arguments arrived in 4.4, a route can also pass a role requirement such as ‘tenant: admin’. If you use filters for protection, avoid legacy auto-routing, because the official documentation warns that a controller may be reachable through URLs you did not anticipate.
4. Keeping the Active Tenant Consistent Across User Sessions
GoodCI44 login security starts at the moment of authentication. Call session()->regenerate() once the membership checks pass, so a session ID obtained before login is useless afterwards. CodeIgniter’s session settings let you tune $expiration and whether regeneration destroys the old session data, and session()->destroy() handles logout.
Store the active tenant ID in the session, but do not treat it as permanent proof. Priya’s membership could be revoked at noon while her session lasts until evening. The filter above handles this by checking the membership table on every protected request. If that cost matters at scale, cache the result briefly and keep the window short.
When a membership is revoked or expires, the next request should fail the filter, clear the tenant data from the session, and redirect appropriately. Session storage alone is not a security mechanism. It remembers who the user was at login, while the database decides what they may do now. Server-side session handlers also make it possible to invalidate a removed user’s sessions from the application, though you must design that behaviour yourself.
5. Preventing Access to Another Tenant’s Records After Login
Suppose Priya, working in Northwind’s workspace, edits /app/invoices/4812 to /app/invoices/4813, and invoice 4813 belongs to another tenant. Her login was perfect, and the filter passed, yet the data leaks if the controller loads the record by ID alone. Protecting the login page does not guarantee isolation.
The fix is to scope every query to the active tenant and to treat a miss as “not found”:
php
use CodeIgniter\Exceptions\PageNotFoundException;
$invoice = (new InvoiceModel())
->where('tenant_id', service('tenantContext')->id())
->find($id);
if ($invoice === null) {
throw PageNotFoundException::forPageNotFound();
}
A 404 avoids confirming that the record exists elsewhere. Many teams put this scoping in a shared base model so no developer has to remember it.
The same discipline applies to every other path into your data:
- API endpoints: derive the tenant from the verified context and re-check membership, rather than accepting a tenant ID in the body.
- Background jobs and Spark commands: these have no session or filter, so pass the tenant explicitly and load it from trusted records.
- Record ownership: validate that any related IDs submitted in a request, such as a customer attached to an invoice, belong to the same tenant.
6. When Users Belong to Multiple Organisations
Priya’s workflow includes switching from Northwind to another client several times a day. Treat each switch as a fresh authorisation decision:
- Accept the switch request as a CSRF-protected POST.
- Look up an active membership for the destination tenant.
- Regenerate the session ID and replace the active tenant.
- Clear tenant-specific session data, such as saved filters, selected records, and cached permissions.
- Load the role and permissions from the destination membership.
Her role at Northwind may be administrator while her role elsewhere is read-only, so permissions must never carry across. With subdomain-based tenancy, a session cookie shared across subdomains can make the same session valid on several tenant hosts. That convenience is safe only because the filter checks membership on each request, and it is worth deciding deliberately rather than by default.
7. Test the Access Boundaries, Not Just the Login Form
Login tests prove that valid users get in. The tests that protect tenants prove that everyone else stays out. CodeIgniter’s feature testing tools, including FeatureTestTrait and withSession(), let you simulate requests as specific users. Cover these cases:
- A user requesting another tenant’s record by ID.
- A removed member reusing an existing session.
- A user switching to a tenant they do not belong to.
- A manipulated tenant identifier in an API request.
- Two tenants granting different permissions to similar roles.
- A protected route that is missing the tenant filter.
Assert both outcomes in every scenario: the allowed request returns the data, and the denied request returns a 403 or 404 with no data in the response. A suite that only tests success cannot detect a leak.
Make Every Authenticated Request Tenant-Aware
Authentication proves who the user is. Membership shows which organisations they belong to, and authorisation decides what they can do in the active one. A secure multi-tenant application checks all three on every request, from login through filters, queries, and background jobs.
If you are planning a secure multi-tenant product, Pennine Technolabs can help you design and build it. You can hire a CodeIgniter developer from our team or explore our CodeIgniter development services in the USA.