In a B2B SaaS app, "Laravel SSO" usually means enterprise SSO: letting each customer's employees sign in to your Laravel app through their company's identity provider, such as Okta or Microsoft Entra ID, over SAML or OpenID Connect (OIDC). Laravel doesn't include this. You add it with a SAML or OIDC package and a per-customer connection model, or you hand it to a CIAM provider.
People also use "SSO" for two other things, so start by checking which one you need:
| You want | What it's called | Laravel tool |
|---|---|---|
| Each customer company signs in with its own IdP (Okta, Entra ID, Google Workspace) | Enterprise SSO (SAML or OIDC) | A SAML or OIDC package, or a CIAM provider |
| Users sign in with Google, GitHub, LinkedIn and similar accounts | Social login | Laravel Socialite |
| Users sign in once across several apps you own | SSO between your own apps | An OAuth server such as Laravel Passport, or a CIAM provider |
This guide covers the first: enterprise SSO for a multi-tenant Laravel app. For Laravel's built-in login, sessions and API tokens, see our Laravel authentication guide.
How enterprise SSO works in a multi-tenant Laravel app
Every customer company (tenant) brings its own identity provider, so your app holds one SSO connection per tenant. A login goes like this:
- Find the tenant. The user enters an email address or opens a tenant-specific URL. Your app looks up the tenant, for example from a verified email domain.
- Start SSO with that tenant's connection. Your app redirects the browser to the tenant's IdP with a SAML request or an OIDC authorization request.
- The user signs in at their IdP. The company's own policies apply: their password rules, MFA and device checks.
- Handle the callback. The IdP sends the user back with a signed SAML assertion or an OIDC authorization code. Your app validates it against that tenant's connection only.
- Link the identity to a user. Find or create the Laravel user and their membership in that tenant.
- Start a Laravel session and set the current tenant.
- Authorize every request against that tenant, so a user from one customer can never see another customer's data.
SAML vs OIDC for Laravel apps
| SAML 2.0 | OpenID Connect (OIDC) | |
|---|---|---|
| Format | XML assertions, posted by the browser | JSON tokens (JWT ID token) via an authorization code |
| Your app's role | Service provider (SP) | Relying party (RP), an OAuth client |
| Customer setup | Exchange metadata: entity ID, ACS URL, signing certificate | Issuer URL, client ID and client secret |
| Common with | ADFS, legacy and on-premises IdPs | Google Workspace and newer app integrations |
| PHP effort | Higher: XML signatures, certificates, clock skew | Lower: standard JWT validation and discovery |
Okta and Microsoft Entra ID support both. Most B2B apps eventually need both protocols, because enterprise customers choose. Read more in our guides to SAML and OIDC.
Building enterprise SSO in Laravel
The examples below were tested on Laravel 13 with PHP 8.4. They show the shape of a working setup, not a complete product.
Store one SSO connection per tenant
Keep connection settings in the database, not in .env, because every customer has their own. Encrypt secrets at rest with Laravel's encrypted cast:
// app/Models/SsoConnection.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SsoConnection extends Model
{
protected $fillable = ['tenant_id', 'slug', 'protocol', 'issuer', 'client_id', 'client_secret', 'verified_domains'];
protected function casts(): array
{
return [
'client_secret' => 'encrypted',
'verified_domains' => 'array',
];
}
}
Find the tenant from the email domain
Only route a domain to a connection after the customer proves they own it, for example with a DNS TXT record, and allow each domain on one connection only. Otherwise anyone could claim yourcustomer.com and capture their users' logins.
use App\Models\SsoConnection;
use Illuminate\Support\Str;
$request->validate(['email' => ['required', 'email']]);
$domain = strtolower(Str::after($request->input('email'), '@'));
$connection = SsoConnection::whereJsonContains('verified_domains', $domain)->first();
if (! $connection) {
return back()->withErrors(['email' => 'Your company has not set up SSO.']);
}
return redirect()->route(
$connection->protocol === 'saml' ? 'saml.login' : 'oidc.login',
$connection->slug
);
OIDC login per tenant
This example uses facile-it/php-openid-client, which handles discovery, signature checks and the iss, aud, exp and nonce claims. Two things it leaves to you: checking state, and passing the nonce back in.
// routes/web.php
use App\Http\Controllers\OidcController;
Route::get('/login/{tenant}', [OidcController::class, 'redirect'])->name('oidc.login');
Route::get('/callback/{tenant}', [OidcController::class, 'callback'])->name('oidc.callback');
// app/Http/Controllers/OidcController.php
namespace App\Http\Controllers;
use App\Models\SsoConnection;
use App\Models\SsoIdentity;
use App\Models\User;
use Facile\OpenIDClient\Client\ClientBuilder;
use Facile\OpenIDClient\Client\Metadata\ClientMetadata;
use Facile\OpenIDClient\Issuer\IssuerBuilder;
use Facile\OpenIDClient\Service\Builder\AuthorizationServiceBuilder;
use Facile\OpenIDClient\Session\AuthSession;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class OidcController
{
public function redirect(string $tenant)
{
$connection = SsoConnection::where('slug', $tenant)->firstOrFail();
$state = Str::random(40);
$nonce = Str::random(40);
session(["oidc.$tenant" => compact('state', 'nonce')]);
$url = (new AuthorizationServiceBuilder())->build()->getAuthorizationUri(
$this->client($connection),
['scope' => 'openid email profile', 'state' => $state, 'nonce' => $nonce]
);
return redirect()->away($url);
}
public function callback(Request $request, string $tenant)
{
$connection = SsoConnection::where('slug', $tenant)->firstOrFail();
$saved = $request->session()->pull("oidc.$tenant");
abort_if($request->query('error'), 401);
abort_unless($saved && hash_equals($saved['state'], (string) $request->query('state')), 401);
try {
$tokens = (new AuthorizationServiceBuilder())->build()->callback(
$this->client($connection),
$request->only(['code', 'state']),
null,
AuthSession::fromArray($saved)
);
} catch (\Throwable $e) {
abort(401);
}
$claims = $tokens->claims();
// Only accept verified emails from this connection's verified domains.
$email = strtolower($claims['email'] ?? '');
abort_unless(
($claims['email_verified'] ?? false)
&& in_array(Str::after($email, '@'), $connection->verified_domains, true),
403
);
// Link by issuer + subject. Never attach a new identity to an existing user automatically.
$identity = SsoIdentity::firstOrNew(['issuer' => $claims['iss'], 'subject' => $claims['sub']]);
if (! $identity->exists) {
abort_if(User::where('email', $email)->exists(), 409, 'Sign in with your existing method to link SSO.');
$user = User::create([
'email' => $email,
'name' => $claims['name'] ?? $email,
'password' => Str::password(),
]);
$identity->user()->associate($user)->save();
}
$user = $identity->user;
$user->tenants()->syncWithoutDetaching([$connection->tenant_id]);
Auth::login($user);
$request->session()->regenerate();
$request->session()->put('tenant_id', $connection->tenant_id);
return redirect()->intended('/dashboard');
}
private function client(SsoConnection $connection)
{
$issuer = (new IssuerBuilder())->build($connection->issuer);
return (new ClientBuilder())
->setIssuer($issuer)
->setClientMetadata(ClientMetadata::fromArray([
'client_id' => $connection->client_id,
'client_secret' => $connection->client_secret,
'token_endpoint_auth_method' => 'client_secret_basic',
'redirect_uris' => [route('oidc.callback', $connection->slug)],
]))
->build();
}
}
In production, cache each tenant's discovery document and signing keys instead of fetching them on every login. Also make sure APP_URL matches the host users see, because the callback URL is built from it.
SAML login per tenant
For SAML, scaler-tech/laravel-saml2 (the maintained successor to 24slides/laravel-saml2) stores one IdP per tenant and gives each tenant its own metadata, login and ACS URLs:
composer require scaler-tech/laravel-saml2
php artisan vendor:publish --provider="Slides\Saml2\ServiceProvider"
php artisan migrate
php artisan saml2:create-tenant --key=acme \
--entityId=https://idp.acme.example/entity \
--loginUrl=https://idp.acme.example/sso \
--logoutUrl=https://idp.acme.example/slo \
--x509cert="MIIC...customer-signing-cert..."
The command prints the SP entity ID and ACS URL to give the customer's IT team. The package's URLs use the tenant's UUID, not its --key, so save that UUID as the SAML connection's slug; otherwise the domain lookup's saml.login redirect returns a 404. When a user signs in, the package fires a SignedIn event; listen for it and run the same domain check, linking and session steps as the OIDC callback above. The package leaves replay protection to you: reject any assertion ID ($event->getAuth()->getLastMessageId()) you have already seen.
A few things to set before going live:
- Set
proxyVarstotrueinconfig/saml2.phpand configure trusted proxies. The package builds URLs from the request host. Behind a load balancer, a mismatch makes every assertion fail the audience check. - Require signed assertions (
wantAssertionsSigned) and replace the placeholder organization details inconfig/saml2.php. - Add the
webmiddleware and exclude the ACS and logout routes from CSRF. SetroutesMiddlewareto['web']inconfig/saml2.php, or the session yourSignedInlistener starts is never saved. Then excludesaml2/*/acsandsaml2/*/slsfrom CSRF inbootstrap/app.php, because the IdP posts to them. - Catch malformed responses. A broken
SAMLResponsethrows an exception; show the user an error page instead of a 500. - Watch the XML-signature dependency. This package relies on onelogin/php-saml and robrichards/xmlseclibs. A critical xmlseclibs advisory is fixed only in xmlseclibs 4, and php-saml 4.4.1 (released November 4, 2026) is the first PHP 8 release that requires it. A fresh install gets php-saml 4.4.1 with xmlseclibs 4.0.1. In an existing app, run
composer update onelogin/php-saml robrichards/xmlseclibs -Wand check thatcomposer show robrichards/xmlseclibsreports 4.x. If Composer keeps you on 3.1.x, another package is holding phpseclib back: xmlseclibs 4 needs phpseclib 3, while laravel/socialite 5.30.1 and later need phpseclib 4. SAML libraries need this kind of ongoing attention.
Provision and deprovision users
SSO alone creates users when they first sign in (just-in-time provisioning), but it never removes anyone. When an employee leaves the customer company, they keep access until their Laravel session expires, and their account stays. Enterprise customers fix this with SCIM: their IdP calls your API to create, update and deactivate users. Plan for a SCIM endpoint per tenant if you sell to larger companies.
Authorize every request by tenant
Signing in proves who the user is, not what they can see. Check tenant membership on every request:
// app/Http/Middleware/EnsureTenantMember.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureTenantMember
{
public function handle(Request $request, Closure $next): Response
{
$tenantId = $request->session()->get('tenant_id');
abort_unless($tenantId && $request->user()?->tenants()->whereKey($tenantId)->exists(), 403);
return $next($request);
}
}
Then scope every query to the current tenant, for example with an Eloquent global scope.
Security checklist and tests
Before you turn SSO on for a customer, test these cases:
- A user from tenant A can't sign in through tenant B's connection, and can't reach tenant B's data after signing in.
- An unverified email domain can't be routed to a connection.
- A replayed SAML assertion or OIDC code is rejected, as are an expired token, a wrong audience and a tampered signature.
- Clock skew between your servers and the IdP is within the library's tolerance.
- Rotating a customer's signing certificate doesn't break other tenants.
- A user who belongs to two tenants lands in the right one.
- Logging out ends the Laravel session, and SCIM deactivation blocks the next request.
- Users of a tenant that enforces SSO can't sign in with a password or use password reset to get around it.
Social login with Laravel Socialite
If you need social login instead, Laravel Socialite supports Facebook, X, LinkedIn, Google, GitHub, GitLab, Bitbucket and Slack out of the box, and the community Socialite Providers project adds many more. Install it with composer require laravel/socialite, put each provider's client_id, client_secret and redirect in config/services.php, then use two routes:
use Laravel\Socialite\Socialite;
Route::get('/auth/redirect', function () {
return Socialite::driver('github')->redirect();
});
Route::get('/auth/callback', function () {
$githubUser = Socialite::driver('github')->user();
// Find or create the user, then Auth::login($user).
});
For local testing, Google accepts http://localhost redirect URIs, so you don't need a live domain or a certificate.
Using a CIAM provider instead
Building per-tenant SSO means owning connection storage, domain verification, SAML and OIDC libraries, certificate rotation, SCIM endpoints, and the admin screens customers use to set it all up. A CIAM provider handles those parts.
With Frontegg, your Laravel app connects to one OpenID Connect provider:
- Hosted login. Your app redirects to Frontegg's hosted login with the authorization code flow, using any PHP OIDC client. Frontegg routes each user to their company's SAML or OIDC identity provider.
- Token validation in Laravel. Your API validates the JWTs Frontegg issues, checking the signature, issuer, audience and expiry. Our Laravel authentication guide includes a tested middleware.
- Customer self-service. Each customer's admins set up their own SAML or OIDC connection, verify their domain and connect SCIM provisioning in Frontegg's admin portal.
Your app still handles the redirect, the callback and tenant-scoped authorization, but not the per-customer IdP plumbing.
FAQ
Does Laravel Socialite support SAML?
Not in its core providers. A community SAML2 provider exists on Socialite Providers, but it targets a single IdP. For one IdP per customer, use a multi-tenant SAML package or a CIAM provider.
Should I use SAML or OIDC?
Support whatever your customers' IdPs require. OIDC is simpler to implement in PHP; SAML is still common in enterprise IdPs. Many B2B apps support both.
Do I need SCIM if I have SSO?
If you sell to larger companies, usually yes. SSO creates users when they sign in but doesn't remove them when they leave the company. SCIM lets the customer's IdP deactivate them in your app.
Can Laravel Passport do enterprise SSO?
No. Passport makes your Laravel app an OAuth 2.0 server that issues tokens. Enterprise SSO is the opposite: your app trusts tokens or assertions from each customer's identity provider.
Put this into practice with Frontegg
Frontegg is customer identity and access management (CIAM) for B2B SaaS. It's free up to 7,500 monthly active users, including 5 SSO/SCIM connections.
Start for free