The first enterprise customer's SSO works. Then the second one signs, then a tenth, and the login page becomes the problem. One email box and one password box no longer make sense. A user at acme.com should be sent to Acme's Okta. A user at globex.io should go to Microsoft Entra ID. A freelancer with a Gmail address invited into Acme's workspace should still be able to log in with a password, and Acme's own admin must not be able to bypass SSO by typing a password. All of that has to happen from one email field, without telling an attacker which companies use your product.
That routing step is usually called home realm discovery (HRD). This post covers how I build it in a multi-tenant SaaS app, and how I turn on "enforced SSO" for a tenant without locking anyone out.
I wrote this with help from AI tools and checked the behaviour against the Okta, Microsoft Entra and WorkOS documentation on domain verification and HRD. I am a Principal Software Engineer in Karachi with 9+ years building Laravel, Node and .NET SaaS backends, and everything here is defensive design for your own application.
📚 Series Navigation — Enterprise SSO & Identity for B2B SaaS
- Part 1: Enterprise SSO Readiness: SAML vs OIDC for B2B SaaS
- Part 2: Validating SAML Responses: Signatures, Audience & Clock Skew
- Part 3: SCIM Provisioning & Deprovisioning That Actually Removes Access
- Part 4 (This Post): Multi-Tenant Login Routing: Domain Discovery & Enforced SSO
- Part 5: Just-in-Time Provisioning & Role Mapping From IdP Groups
- Part 6: Break-Glass Accounts & SSO Audit Logs
Related earlier posts: Session Lifecycle Hardening: Rotation, Timeouts & Server-Side Revocation · OAuth 2.1 & OIDC ID Tokens: PKCE Forensics
How does a multi-tenant app decide which SSO to use?
Direct answer: Ask for the email first, extract the domain, and look it up in a table of verified domains mapped to tenant SSO connections. If a match exists and SSO is enforced, redirect to that IdP; otherwise show the password or social login step. Only map domains proven by a DNS TXT record, and give the same response for unknown and known domains.
The routing options
| Strategy | User experience | Security notes | Good for |
|---|---|---|---|
Tenant subdomain (acme.app.com) | User must know their URL | Simple; subdomain itself picks the IdP | Apps where users already live on a tenant URL |
| Email-first HRD | One login page for everyone | Needs verified domains and anti-enumeration care | Most B2B SaaS |
| "Log in with SSO" button + company slug | Extra step | Slug reveals customers if guessable | Fallback for shared email domains |
| IdP-initiated (from Okta dashboard) | One click from the IdP | Must still validate response (Part 2) | Customers who launch apps from their portal |
I usually ship email-first HRD as the main path, plus a tenant-slug fallback and support for IdP-initiated login.
Step 1: verify domain ownership before routing anything
Never let a tenant admin claim gmail.com, or a competitor's domain, just by typing it. Issue a token and require a DNS TXT record:
_myapp-verification.acme.com. 300 IN TXT "myapp-domain-verification=7f3c9a1e5b..." public function verify(TenantDomain $d): bool { $records = dns_get_record("_myapp-verification.{$d->domain}", DNS_TXT) ?: []; foreach ($records as $r) { if (hash_equals("myapp-domain-verification={$d->token}", $r['txt'] ?? '')) { $d->forceFill(['verified_at' => now()])->save(); return true; } } return false; } Rules I enforce: block a list of public email providers (gmail.com, outlook.com, yahoo.com and so on), store domains lowercased, allow one verified owner per domain, and re-check the TXT record periodically so a lapsed domain does not keep routing.
Step 2: parse the email domain carefully
Email parsing is where routing bugs hide. Alice@ACME.com, alice@acme.com. (trailing dot), alice+test@acme.com and IDN domains should all route the same way, while alice@acme.com.evil.io must not match acme.com.
function emailDomain(string $email): ?string { $email = trim($email); if (! filter_var($email, FILTER_VALIDATE_EMAIL)) return null; $domain = strtolower(rtrim(substr(strrchr($email, '@'), 1), '.')); return idn_to_ascii($domain, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) ?: null; } // exact match, then parent-domain match for subdomains like eu.acme.com $conn = SsoDomain::verified()->whereIn('domain', candidateDomains($domain))->orderByDesc(DB::raw('LENGTH(domain)'))->first(); Always compare whole labels from the right, never with str_contains or an unanchored regex. When I write the matching pattern, I test it against the nasty cases in a regex tester first, and I check redirect targets with a URL parser to make sure the RelayState or returnTo host is ours and not an open redirect.
Step 3: enforce SSO per tenant, with exceptions
"Enforced SSO" means users with a verified domain of that tenant cannot use a password at all. The decision table I implement:
public function loginMethod(string $email): array { $domain = emailDomain($email); $conn = $domain ? SsoDomain::verified()->forDomain($domain)->first()?->connection : null; if ($conn && $conn->enforced) { return ['method' => 'sso', 'connection' => $conn->id]; // no password path } if ($conn) { return ['method' => 'choice', 'connection' => $conn->id]; // SSO offered, password allowed } return ['method' => 'password']; // guests, Gmail users, non-SSO tenants } The exceptions are where lockouts happen:
- Guests and contractors with outside domains keep password or social login, scoped only to the workspaces that invited them.
- Break-glass owners: one or two named tenant owners keep a hardware-key login in case the IdP breaks. Part 6 covers this.
- Users who belong to several tenants: route by the domain, then after login let them switch only to workspaces whose policy their login method satisfies.
Enforcement must be checked on the server for every login path, including password reset, magic links and API token creation. Hiding the password field in the UI is not enforcement.
Step 4: don't leak your customer list
If alice@acme.com gets "Redirecting to Acme SSO" and alice@random.com gets "No account", anyone can enumerate your customers and their users. Mitigations:
- Return the same shape of response for every email and do the redirect from a generic "Continue" step.
- For password users, always show the password field whether or not the account exists, and give one generic error.
- Rate-limit the discovery endpoint per IP and per email domain.
Some leakage is unavoidable when you redirect to a named IdP, so the realistic goal is to stop bulk enumeration of individual accounts.
Step 5: roll out enforcement safely
Turning on enforcement for a tenant with existing password users is a migration. My order:
- Verify the domain and connect the IdP with enforcement off.
- Show users "Your company now uses SSO" and log which users have signed in via SSO at least once.
- When most active users have, switch enforcement on, revoke password sessions for that domain, and keep break-glass accounts.
- Watch login error rates for a week.
Diagnostic checklist
- [ ] Domains are only routable after DNS TXT verification
- [ ] Public email providers are blocked from being claimed
- [ ] Email domains are normalised (case, trailing dot, IDN) and matched by whole labels
- [ ] Enforced-SSO tenants have no server-side password, reset or magic-link path
- [ ] Guests from outside domains can still log in to the workspaces that invited them
- [ ] Break-glass accounts exist for every enforced tenant
- [ ] Discovery responses do not reveal whether an account exists
- [ ] Redirect and RelayState targets are allow-listed
FAQ
Should I use subdomains or email-first discovery?
Email-first gives a single login page and works for users who do not know their tenant URL. Subdomains are fine if your product already lives on per-tenant URLs. Many apps support both.
What if two tenants share a domain, like two divisions of one company?
Let the domain route to a chooser limited to those tenants, or map it to a parent organisation that holds both workspaces.
Can a tenant enforce SSO for users from another domain?
Only for accounts it owns. A guest from an outside domain is governed by their own login method; the tenant can choose to disallow guests entirely instead.
How do I handle an IdP outage for an enforced tenant?
Break-glass accounts for named owners, plus a support process with strong identity checks. Never a global "disable SSO" switch that anyone can flip.
Does enforced SSO replace SCIM?
No. Enforcement controls how people log in; SCIM (Part 3) controls whether their account still exists and removes existing sessions.
Should the discovery endpoint be cached?
Cache the domain-to-connection lookup briefly, but invalidate it immediately when a domain is removed or enforcement changes.
Next in this series, Part 5 covers just-in-time provisioning and mapping IdP groups to roles in your app.
Follow & Connect
- Website: PixelValut Tools
- Watch on YouTube: Resume Boost AI · PixelValut · Daily AI News By Ali
- TikTok: PixelValut (@pixelvalut007)
- GitHub: Muhammad Ali Mughal (@ali111887)
- LinkedIn: Muhammad Ali Mughal


