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

Saml2 Bridge Bundle Laravel Package

aa-aahmed/saml2-bridge-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require adactive-sas/saml2-bridge-bundle
    

    Ensure your composer.json includes "adactive-sas/saml2-bridge-bundle": "^x.y.z" (replace with latest version).

  2. Bundle Registration: Add to config/bundles.php (Symfony 4.3+):

    return [
        // ...
        AdactiveSas\Saml2BridgeBundle\AdactiveSasSaml2BridgeBundle::class => ['all' => true],
    ];
    
  3. Configuration: Publish the default config:

    php bin/console config:dump-reference AdactiveSasSaml2BridgeBundle
    

    Override in config/packages/adactive_sas_saml2_bridge.yaml:

    adactive_sas_saml2_bridge:
        idp:
            entity_id: "https://yourdomain.com/saml/idp/metadata"
            name: "Your Identity Provider"
            x509cert: "%kernel.project_dir%/config/saml/cert.pem"
            private_key: "%kernel.project_dir%/config/saml/key.pem"
            authn:
                binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    
  4. Metadata Generation: Generate and expose metadata endpoint:

    php bin/console adactive:saml:metadata:generate
    

    Access metadata at /saml/idp/metadata.

  5. First Use Case: Configure a Service Provider (SP) in your SAML IdP dashboard (e.g., Azure AD, Okta) with:

    • Entity ID: https://yourdomain.com/saml/sp/metadata (SP metadata URL)
    • ACS URL: https://yourdomain.com/saml/acs (Assertion Consumer Service)
    • Signing Certificate: Your SP’s public certificate.

Implementation Patterns

Core Workflows

1. SAML Authentication Flow

  • Initiate SSO: Redirect users to SP’s SAML endpoint with:

    use AdactiveSas\Saml2BridgeBundle\Service\SamlService;
    
    $samlService = $this->container->get(SamlService::class);
    $samlService->initiateSso($spEntityId, $returnUrl);
    

    This generates a signed AuthnRequest and redirects to the SP.

  • Handle Assertion Consumer Service (ACS): Override the default ACS controller or use the bundle’s built-in route (/saml/acs):

    // src/Controller/SamlController.php
    use AdactiveSas\Saml2BridgeBundle\Controller\SamlController;
    
    class CustomSamlController extends SamlController
    {
        public function acsAction(Request $request)
        {
            $response = parent::acsAction($request);
            // Custom logic (e.g., user mapping, role assignment)
            return $response;
        }
    }
    

    Register the route in config/routes.yaml:

    saml_acs:
        path: /saml/acs
        controller: App\Controller\CustomSamlController::acsAction
    

2. User Provisioning

Map SAML attributes to Laravel users:

# config/packages/adactive_sas_saml2_bridge.yaml
adactive_sas_saml2_bridge:
    idp:
        attributes:
            username: "urn:oid:0.9.2342.19200300.100.1.1"  # SAML attribute for email
            first_name: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
            last_name: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"

Use the SamlUserProvider to fetch or create users:

$userProvider = $this->container->get('adactive_sas_saml2_bridge.user_provider');
$user = $userProvider->loadUserByUsername($samlAttributes['username']);

3. Single Logout

Trigger logout from your application:

$samlService->initiateLogout($spEntityId, $returnUrl);

Or handle SP-initiated logout at /saml/slo.


Integration Tips

Laravel-Specific Adaptations

  1. Service Container Binding: Bind the bundle’s services to Laravel’s container in AppServiceProvider:

    public function register()
    {
        $this->app->bind(
            AdactiveSas\Saml2BridgeBundle\Service\SamlService::class,
            function ($app) {
                return new SamlService(
                    $app['adactive_sas_saml2_bridge.saml'],
                    $app['adactive_sas_saml2_bridge.user_provider']
                );
            }
        );
    }
    
  2. Middleware for Protected Routes: Create middleware to verify SAML sessions:

    // app/Http/Middleware/VerifySamlSession.php
    public function handle($request, Closure $next)
    {
        if (!$request->hasSession() || !$request->session()->has('saml_authenticated')) {
            return redirect()->route('saml.login');
        }
        return $next($request);
    }
    

    Apply to routes:

    # config/routes.yaml
    _saml_protected:
        path: /protected
        middleware: ['web', 'saml.session']
    
  3. Event Listeners: Listen to SAML events (e.g., SamlAuthenticateEvent) for custom logic:

    // app/Listeners/SamlAuthListener.php
    public function handle(SamlAuthenticateEvent $event)
    {
        $user = $event->getUser();
        // Assign roles, log activity, etc.
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        'AdactiveSas\Saml2BridgeBundle\Event\SamlAuthenticateEvent' => [
            'App\Listeners\SamlAuthListener',
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. Certificate Management:

    • Private Key Format: The bundle expects the private key in PEM format (no passphrase). Convert using:
      openssl rsa -in key.pem -out key_no_pass.pem
      
    • Certificate Validity: Ensure certificates are valid and not expired. Test with:
      openssl x509 -in cert.pem -noout -dates
      
  2. Metadata Mismatches:

    • Entity ID Conflicts: Double-check entity_id in both SP and IdP configurations. Use absolute URLs.
    • Clock Skew: SAML messages include timestamps. Ensure server clocks are synchronized (NTP).
  3. Debugging SAML Errors:

    • Enable debug logging in config/packages/monolog.yaml:
      handlers:
          saml:
              type: stream
              path: "%kernel.logs_dir%/saml.log"
              level: debug
              channels: ["saml"]
      
    • Check logs for errors like:
      • Invalid signature: Certificate or key misconfiguration.
      • Message expired: Clock skew or NotOnOrAfter validation.
  4. Attribute Mapping:

    • Missing Attributes: If SAML responses lack expected attributes, verify:
      • The SP is configured to send the correct attributes.
      • The attribute names match the SAML standard (e.g., urn:oid:... for OIDs).
  5. Session Handling:

    • Session Fixation: Clear the session after SAML logout:
      $request->getSession()->invalidate();
      

Tips

  1. Testing:

    • Use SimpleSAMLphp as a test SP for development:
      docker run --rm -p 8080:80 -v $(pwd)/saml:/var/www/simplesaml simplesamlphp/simplesamlphp:latest
      
    • Configure the SP in config/simplesamlphp/metadata/saml20-sp-hosted.php.
  2. Performance:

    • Cache metadata to avoid regenerating on every request:
      # config/packages/adactive_sas_saml2_bridge.yaml
      adactive_sas_saml2_bridge:
          cache_metadata: true
          metadata_cache_lifetime: 3600  # 1 hour
      
  3. Security:

    • Disable Debug Mode: Set debug: false in production config.
    • HTTPS Enforcement: Ensure all SAML endpoints use HTTPS. Add middleware:
      $this->app->middleware(EnsureHttps::class);
      
  4. Customization:

    • Override Templates: Extend the bundle’s Twig templates (e.g., login forms) by copying from: `vendor
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky