## Getting Started
### Minimal Setup
1. **Installation**
```bash
composer require aacotroneo/laravel-saml2
For Laravel <5.5, manually register Aacotroneo\LaravelSaml2\LaravelSaml2ServiceProvider in config/app.php.
Publish Config
php artisan vendor:publish --provider="Aacotroneo\LaravelSaml2\LaravelSaml2ServiceProvider"
This generates config/saml2.php. Configure your Identity Provider (IdP) metadata (e.g., entityId, singleSignOnService, x509cert) and Service Provider (SP) settings (e.g., strict, debug, nameIdFormat).
First Use Case: Authentication Route Add a route to trigger SAML authentication:
Route::get('/login/saml', 'Auth\SamlController@login')->name('saml.login');
Handle the response in a controller:
use Aacotroneo\LaravelSaml2\Facades\LaravelSaml2;
public function login()
{
return LaravelSaml2::redirectToIdp();
}
public function callback()
{
$attributes = LaravelSaml2::processResponse();
if ($attributes) {
// Map attributes to user (e.g., email, name)
$user = User::firstOrCreate(['email' => $attributes['email']]);
auth()->login($user);
return redirect()->intended('/dashboard');
}
return redirect()->route('saml.login')->with('error', 'SAML authentication failed');
}
Callback Route
Ensure your callback route (e.g., /saml/callback) is publicly accessible and matches the assertionConsumerService in your SP config.
Authentication Flow
LaravelSaml2::redirectToIdp().LaravelSaml2::processResponse() to parse the SAML response.email, nameId) to create/update a local user or link to an existing account.
$attributes = LaravelSaml2::getAttributes();
$user = User::updateOrCreate(
['email' => $attributes['email'][0] ?? null],
['name' => $attributes['name'][0] ?? null]
);
Single Logout (SLO)
LaravelSaml2::performSingleLogout().public function sloCallback()
{
LaravelSaml2::processSingleLogoutRequest();
auth()->logout();
return redirect('/');
}
Metadata Handling
LaravelSaml2::getSpMetadata() to generate SP metadata for IdP configuration.https://idp.example.com/saml/metadata) and configure saml2.php manually or via a helper:
$metadata = simplexml_load_file('idp-metadata.xml');
$config = [
'idp' => [
'entityId' => (string)$metadata->EntityDescriptor->EntityID,
'singleSignOnService' => (string)$metadata->EntityDescriptor->IDPSSODescriptor->SingleSignOnService->Location,
'x509cert' => (string)$metadata->EntityDescriptor->IDPSSODescriptor->KeyDescriptor[0]->KeyInfo->X509Data->X509Certificate,
],
];
Attribute Mapping
saml2.php:
'attribute_map' => [
'email' => 'emailaddress',
'name' => 'fullname',
'groups' => 'memberof',
],
LaravelSaml2::extend('process_response', function ($response) {
// Custom logic (e.g., decrypt assertions)
return $this->defaultProcessResponse($response);
});
auth middleware.database or redis) for state management.LaravelSaml2::setTestMode(true) to mock responses for unit tests:
LaravelSaml2::setTestResponse([
'email' => ['test@example.com'],
'name' => ['Test User'],
]);
'debug' => true) to log SAML messages to storage/logs/saml.log.Metadata Mismatch
AssertionConsumerService or entityId.assertionConsumerService in saml2.php matches the callback URL (e.g., https://your-app.com/saml/callback). Use LaravelSaml2::getSpMetadata() to validate SP metadata.Certificate Errors
'strict' => false) for testing, or import the IdP cert into Laravel’s trusted store:
$cert = file_get_contents('idp-cert.pem');
file_put_contents(storage_path('app/saml/idp-cert.pem'), $cert);
Update saml2.php to point to the local cert:
'idp' => [
'x509cert' => file_get_contents(storage_path('app/saml/idp-cert.pem')),
],
Attribute Parsing
email is missing).attribute_map in saml2.php. Use LaravelSaml2::getAttributes() to inspect raw attributes:
dd(LaravelSaml2::getAttributes());
Session Expiry
LaravelSaml2::setSessionLifetime():
LaravelSaml2::setSessionLifetime(3600); // 1 hour
Deprecated Laravel Versions
24Slides/laravel-saml2 or manually patch the OneLogin/php-saml dependency.'debug' => true in saml2.php to log SAML messages to storage/logs/saml.log.LaravelSaml2::setTestMode(true) to simulate SAML responses for development:
LaravelSaml2::setTestResponse([
'email' => ['user@example.com'],
'name' => ['Test User'],
]);
Custom Auth Logic
LaravelSaml2::extend('post_auth', function ($user, $attributes) {
// Custom logic (e.g., role assignment)
$user->assignRole($attributes['groups'][0] ?? 'default');
});
Dynamic IdP Configuration
$idpConfig = IdPConfig::where('name', 'AzureAD')->first();
LaravelSaml2::setIdpConfig($idpConfig->toArray());
Custom Error Handling
App\Exceptions\Handler:
catch (\OneLogin\Saml2\Error\Error as $e) {
\Log::error('SAML Error: ' . $e->getMessage());
return back()->with('error', 'SAML authentication failed. Please try again.');
}
Multi-IdP Support
public function login($idp = 'default')
{
$config = config("saml2.idps.{$idp}");
Laravel
How can I help you explore Laravel packages today?