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

Lightsaml Bundle Laravel Package

claroline/lightsaml-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle via Composer:
   ```bash
   composer require claroline/lightsaml-bundle

Enable it in config/bundles.php:

return [
    // ...
    LightSaml\SpBundle\LightSamlSpBundle::class => ['all' => true],
];
  1. Configuration Publish the default config and adjust config/packages/lightsaml_sp.yaml:

    php bin/console lightsaml:sp:install
    

    Key settings:

    • sp.entity_id: Your SP entity ID (e.g., urn:myapp:sp).
    • sp.assertion_consumer_service.url: Redirect URL after SAML auth (e.g., /saml/acs).
    • idp.metadata: Path to IdP metadata file or URL (e.g., https://idp.example.com/metadata.xml).
  2. First Use Case Trigger SAML login via a route or controller:

    use LightSaml\SpBundle\Controller\SpController;
    
    // In your controller:
    return $this->redirectToRoute('lightsaml_sp_login');
    

    The bundle handles the SAML flow automatically, redirecting to the IdP and back to your ACS.


Implementation Patterns

Core Workflows

  1. Authentication Flow

    • Login: Redirect users to IdP via lightsaml_sp_login route.
    • ACS (Assertion Consumer Service): Handle SAML responses at /saml/acs (configured in sp.assertion_consumer_service.url).
    • Logout: Use lightsaml_sp_logout route to trigger IdP-initiated logout (if configured).
  2. Metadata Management

    • Dynamic Metadata: Generate SP metadata on-the-fly:
      php bin/console lightsaml:sp:metadata
      
    • IdP Metadata: Fetch or upload IdP metadata via CLI:
      php bin/console lightsaml:sp:metadata:import --url="https://idp.example.com/metadata.xml"
      
  3. User Mapping Customize user resolution in config/packages/lightsaml_sp.yaml:

    sp:
        user:
            class: App\Entity\User
            property_mappings:
                - {idp_attribute: "uid", user_property: "username"}
                - {idp_attribute: "mail", user_property: "email"}
    

    Override the default UserProvider to implement custom logic:

    // src/Service/CustomUserProvider.php
    use LightSaml\SpBundle\Security\User\UserProviderInterface;
    
    class CustomUserProvider implements UserProviderInterface {
        public function loadUserBySAMLAttributes(array $attributes) {
            // Custom logic to fetch/create user
        }
    }
    

    Register it in config/packages/lightsaml_sp.yaml:

    sp:
        user:
            provider: App\Service\CustomUserProvider
    
  4. Attribute Handling Access SAML attributes in controllers or services via the LightSaml\SpBundle\Security\Authentication\Token\SAMLToken:

    $token = $this->get('security.token_storage')->getToken();
    $attributes = $token->getAttributes();
    
  5. CSRF Protection Enable CSRF protection in lightsaml_sp.yaml:

    sp:
        acs:
            require_csrf: true
    

Integration Tips

  • Symfony Security Component The bundle integrates with Symfony’s security system. Use it alongside firewalls:

    # config/packages/security.yaml
    firewalls:
        main:
            pattern: ^/
            saml: true  # Enables SAML auth
            form_login: ~  # Fallback if SAML fails
    
  • Custom Routes Extend the bundle’s routes by overriding the lightsaml_sp.yaml configuration:

    sp:
        routes:
            login: app_saml_login  # Custom route name
            acs: app_saml_acs      # Custom ACS endpoint
    
  • Testing Mock SAML responses in tests using the LightSaml\SpBundle\Tests\Mock\SAMLResponseMock or libraries like php-saml:

    $mockResponse = new SAMLResponseMock();
    $this->client->request('POST', '/saml/acs', [
        'SAMLResponse' => $mockResponse->getResponse(),
    ]);
    

Gotchas and Tips

Common Pitfalls

  1. Metadata Mismatches

    • Issue: SAML errors due to mismatched entity_id or AssertionConsumerService URLs.
    • Fix: Verify sp.entity_id and sp.assertion_consumer_service.url match the IdP’s expectations. Use the CLI to generate metadata and compare:
      php bin/console lightsaml:sp:metadata > sp-metadata.xml
      
  2. Time Synchronization

    • Issue: SAML responses rejected due to clock skew (e.g., IdP and SP clocks out of sync).
    • Fix: Ensure both servers use NTP or a reliable time source. Adjust sp.security settings if needed:
      sp:
          security:
              max_time_difference: 300  # Allow 5-minute skew
      
  3. Attribute Mapping Failures

    • Issue: User not created/resolved due to missing or mismapped attributes.
    • Fix: Debug with:
      $token = $this->get('security.token_storage')->getToken();
      dump($token->getAttributes()); // Check received attributes
      
    • Ensure property_mappings in lightsaml_sp.yaml match the IdP’s attribute names.
  4. HTTPS Requirements

    • Issue: SAML requests fail in production due to missing HTTPS.
    • Fix: Configure the bundle to enforce HTTPS:
      sp:
          security:
              enforce_https: true
      
    • Ensure your IdP metadata uses HTTPS URLs.
  5. Session Handling

    • Issue: Users logged out unexpectedly after SAML auth.
    • Fix: Configure session lifetime in framework.session and ensure sp.session settings align:
      sp:
          session:
              lifetime: 3600  # 1 hour
      

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/dev/lightsaml_sp.yaml:

    sp:
        debug: true
    

    Logs appear in var/log/dev.log.

  2. SAML Message Inspection Use tools like SAML Tracer to inspect SAML requests/responses in browser dev tools.

  3. CLI Commands

    • Validate metadata:
      php bin/console lightsaml:sp:validate-metadata
      
    • Test SAML auth flow manually:
      php bin/console lightsaml:sp:login
      

Extension Points

  1. Custom Authenticators Extend LightSaml\SpBundle\Security\Authenticator\SAMLAuthenticator to add pre/post-auth logic:

    use LightSaml\SpBundle\Security\Authenticator\SAMLAuthenticatorInterface;
    
    class CustomSAMLAuthenticator implements SAMLAuthenticatorInterface {
        public function authenticate(Request $request) {
            // Custom logic (e.g., validate additional claims)
        }
    }
    

    Register it in lightsaml_sp.yaml:

    sp:
        authenticator: App\Security\Authenticator\CustomSAMLAuthenticator
    
  2. Event Listeners Listen to SAML events (e.g., lightsaml.sp.security.interactive_login):

    // src/EventListener/SAMLListener.php
    use LightSaml\SpBundle\Event\SAMLEvents;
    
    class SAMLListener {
        public function onSAMLLogin(InteractiveLoginEvent $event) {
            // Custom logic on successful login
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\SAMLListener:
            tags:
                - { name: kernel.event_listener, event: lightsaml.sp.security.interactive_login, method: onSAMLLogin }
    
  3. Custom Metadata Providers Override the default metadata provider to fetch IdP metadata dynamically:

    use LightSaml\SpBundle\Metadata\MetadataProviderInterface;
    
    class CustomMetadataProvider implements MetadataProviderInterface {
        public function getIdPMetadata() {
            // Fetch from API/database, etc.
        }
    }
    

    Register in lightsaml_sp.yaml:

    sp:
        metadata:
            idp_provider: App\Metadata\CustomMetadataProvider
    

Configuration Quirks

  1. Dynamic IdP Selection To support multiple IdPs, use a switchyard configuration:
    sp:
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware