Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Saml2 Laravel Package

aacotroneo/laravel-saml2

View on GitHub
Deep Wiki
Context7
## 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.

  1. 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).

  2. 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');
    }
    
  3. Callback Route Ensure your callback route (e.g., /saml/callback) is publicly accessible and matches the assertionConsumerService in your SP config.


Implementation Patterns

Workflows

  1. Authentication Flow

    • Initiate Login: Redirect user to IdP via LaravelSaml2::redirectToIdp().
    • Process Response: After IdP redirects back, call LaravelSaml2::processResponse() to parse the SAML response.
    • User Mapping: Use attributes (e.g., 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]
      );
      
  2. Single Logout (SLO)

    • Trigger logout via LaravelSaml2::performSingleLogout().
    • Handle SLO response in a callback route:
      public function sloCallback()
      {
          LaravelSaml2::processSingleLogoutRequest();
          auth()->logout();
          return redirect('/');
      }
      
  3. Metadata Handling

    • Dynamic Metadata: Use LaravelSaml2::getSpMetadata() to generate SP metadata for IdP configuration.
    • IdP Metadata: Parse IdP metadata XML (e.g., from 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,
          ],
      ];
      
  4. Attribute Mapping

    • Customize attribute handling in saml2.php:
      'attribute_map' => [
          'email' => 'emailaddress',
          'name' => 'fullname',
          'groups' => 'memberof',
      ],
      
    • Override default processing in a service:
      LaravelSaml2::extend('process_response', function ($response) {
          // Custom logic (e.g., decrypt assertions)
          return $this->defaultProcessResponse($response);
      });
      

Integration Tips

  • Middleware: Protect routes post-SAML login with auth middleware.
  • Session: Ensure session driver is configured (e.g., database or redis) for state management.
  • Testing: Use LaravelSaml2::setTestMode(true) to mock responses for unit tests:
    LaravelSaml2::setTestResponse([
        'email' => ['test@example.com'],
        'name' => ['Test User'],
    ]);
    
  • Logging: Enable debug mode ('debug' => true) to log SAML messages to storage/logs/saml.log.

Gotchas and Tips

Pitfalls

  1. Metadata Mismatch

    • Issue: IdP rejects requests due to mismatched AssertionConsumerService or entityId.
    • Fix: Verify assertionConsumerService in saml2.php matches the callback URL (e.g., https://your-app.com/saml/callback). Use LaravelSaml2::getSpMetadata() to validate SP metadata.
  2. Certificate Errors

    • Issue: IdP certificate validation fails (e.g., expired or self-signed certs).
    • Fix: Disable strict validation temporarily ('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')),
      ],
      
  3. Attribute Parsing

    • Issue: Attributes are not being mapped correctly (e.g., email is missing).
    • Fix: Check the IdP’s attribute naming conventions and update attribute_map in saml2.php. Use LaravelSaml2::getAttributes() to inspect raw attributes:
      dd(LaravelSaml2::getAttributes());
      
  4. Session Expiry

    • Issue: SAML session expires before the user’s Laravel session.
    • Fix: Sync sessions by extending the Laravel session lifetime or using LaravelSaml2::setSessionLifetime():
      LaravelSaml2::setSessionLifetime(3600); // 1 hour
      
  5. Deprecated Laravel Versions

    • Issue: Package may not support newer Laravel versions (last release: 2019).
    • Fix: Use a fork like 24Slides/laravel-saml2 or manually patch the OneLogin/php-saml dependency.

Debugging

  • Enable Debugging: Set 'debug' => true in saml2.php to log SAML messages to storage/logs/saml.log.
  • Test Mode: Use LaravelSaml2::setTestMode(true) to simulate SAML responses for development:
    LaravelSaml2::setTestResponse([
        'email' => ['user@example.com'],
        'name' => ['Test User'],
    ]);
    
  • Validate XML: Use online tools (e.g., SAML Tracer) to validate SAML requests/responses.

Extension Points

  1. Custom Auth Logic

    • Override the default auth flow by extending the facade:
      LaravelSaml2::extend('post_auth', function ($user, $attributes) {
          // Custom logic (e.g., role assignment)
          $user->assignRole($attributes['groups'][0] ?? 'default');
      });
      
  2. Dynamic IdP Configuration

    • Load IdP settings from a database or API:
      $idpConfig = IdPConfig::where('name', 'AzureAD')->first();
      LaravelSaml2::setIdpConfig($idpConfig->toArray());
      
  3. Custom Error Handling

    • Catch SAML exceptions globally in 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.');
      }
      
  4. Multi-IdP Support

    • Route users to different IdPs based on a parameter:
      public function login($idp = 'default')
      {
          $config = config("saml2.idps.{$idp}");
          Laravel
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle