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 Laravel Package

litesaml/lightsaml

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require litesaml/lightsaml:^5.0

Requires PHP 8.1+. Note: Version 5.x introduces breaking changes (see Gotchas and Tips).

  1. First Use Case:

    • SAML AuthN Request (SP-initiated login):
      use LiteSaml\Model\AuthnRequest;
      use LiteSaml\Model\Issuer;
      use LiteSaml\Model\NameIdPolicy;
      
      $request = new AuthnRequest();
      $request->setIssuer(new Issuer('https://your-sp.example.com/metadata'));
      $request->setDestination('https://idp.example.com/sso');
      $request->setNameIdPolicy(new NameIdPolicy('urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'));
      $xml = $request->toXml();
      
    • Parse SAML Response (with XSW protection enabled by default):
      use LiteSaml\Model\Response;
      use LiteSaml\Binding\HttpPostBinding;
      
      $response = Response::fromXml($xml);
      $binding = new HttpPostBinding();
      $binding->send($response, 'https://your-sp.example.com/acs');
      
  2. Key Resources:


Implementation Patterns

Core Workflows

  1. SP-Initiated Login:

    • Generate AuthnRequest → Serialize to XML → Send via HttpRedirectBinding.
    • Parse Response from IDP → Validate XSW protection → Authenticate user.
      try {
          $response = Response::fromXml($xml); // Automatically checks XSW invariants
          // Proceed with validation...
      } catch (\LiteSaml\Exception\SecurityException $e) {
          // Handle XSW attack or signature failure
      }
      
  2. IDP-Initiated Login:

    • Parse AuthnRequest from SP → Generate Response → Send via HttpPostBinding.
    • Critical: Ensure ds:Signature in responses adheres to XSW protection rules (see Gotchas).
  3. Metadata Handling (Unchanged):

    • Load IDP/SP metadata (XML) → Extract descriptors (e.g., IdpSsoDescriptor).
      use LiteSaml\Model\Metadata\EntitiesDescriptor;
      $entities = EntitiesDescriptor::fromXml($metadataXml);
      $idpDescriptor = $entities->getByEntityId('https://idp.example.com/metadata');
      
  4. Signature Validation (Updated):

    • XSW Protection: Enabled by default in SignatureValidator (v5+).
      use LiteSaml\Model\XmlDSig\SignatureValidator;
      $validator = new SignatureValidator();
      $validator->addCertificate($idpCertificate);
      $isValid = $validator->validate($response->getSignature());
      // Throws `SecurityException` if XSW attack detected.
      

Integration Tips

  • Laravel Middleware (Updated for v5):

    namespace App\Http\Middleware;
    use LiteSaml\Binding\HttpPostBinding;
    use LiteSaml\Model\Response;
    
    class SamlAuthenticate
    {
        public function handle($request, Closure $next)
        {
            if ($request->isSamlPost()) {
                try {
                    $binding = new HttpPostBinding();
                    $response = $binding->receive($request);
                    // XSW protection is automatic; proceed with validation...
                } catch (\LiteSaml\Exception\SecurityException $e) {
                    \Log::warning("SAML Security Error: " . $e->getMessage());
                    return redirect('/error');
                }
            }
            return $next($request);
        }
    }
    
  • Session Management (Unchanged):

    session(['saml_session_id' => $response->getInResponseTo()]);
    
  • Error Handling (Updated):

    • Catch new LiteSaml\Exception\SecurityException for XSW attacks or signature failures.
    • Use LiteSaml\Exception\ValidationException for malformed messages.
  • Configuration (Recommended for v5):

    config([
        'saml' => [
            'security' => [
                'xsw_protection' => true, // Default: true (enabled)
                'strict_canonicalization' => true, // Recommended for SAML 2.0
            ],
            'sp' => [
                'entity_id' => 'https://your-sp.example.com/metadata',
                'certificate' => file_get_contents('path/to/sp-cert.pem'),
            ],
        ],
    ]);
    

Gotchas and Tips

Pitfalls

  1. XML Security (Critical for v5):

    • XSW Attacks: Default protection enabled. If your IDP’s responses fail validation, check:
      • The ds:Signature parent element must have an Id attribute matching the Signature’s Reference URI.
      • The Id must be unique in the document.
      • Fix: Regenerate IDP certificates or adjust signing logic to comply with RFC 8339.
    • Canonicalization: Use Exclusive XML Canonicalization (default in v5) for SAML 2.0 compliance.
  2. Bindings (Unchanged):

    • Post Bindings: Validate RelayState and SAMLResponse encoding.
    • Redirect Bindings: Sanitize Destination URLs to prevent open redirects.
  3. Time Constraints (Unchanged):

    if ($assertion->getConditions()->getNotOnOrAfter() < now()) {
        throw new \RuntimeException('Expired assertion');
    }
    
  4. Metadata (Unchanged):

    • EntityID Mismatch: Always validate Issuer vs. EntityID.
    • Role Descriptors: Use getByEntityId() safely (see #91).
  5. Breaking Changes in v5:

    • Deprecated: LiteSaml\Context\Context is now immutable. Use LiteSaml\Context\ImmutableContext instead.
    • Removed: LiteSaml\Helper::loadCertificate() is deprecated. Use PHP’s openssl_x509_read() or libraries like webmozart/assert.
    • Schema Validation: XsdValidator is stricter by default. Disable with:
      $validator = new \LiteSaml\Validator\XsdValidator(['strict' => false]);
      

Debugging Tips

  1. XML Dumping (Unchanged):

    echo $request->toXml(); // Debug raw XML
    
  2. XSW Validation Errors:

    • Enable debug logging for LiteSaml\Validator\SignatureXmlValidator:
      \LiteSaml\Validator\SignatureXmlValidator::setDebugMode(true);
      
    • Check logs for messages like:
      SecurityException: XML Signature Wrapping attack detected. Signature ID 'sig-1' does not match parent element ID.
      
  3. Validation Errors (Updated):

    • Use LiteSaml\Validator\CompositeValidator to chain validators:
      $validator = new \LiteSaml\Validator\CompositeValidator([
          new \LiteSaml\Validator\XsdValidator(),
          new \LiteSaml\Validator\SignatureXmlValidator(),
      ]);
      $validator->validate($response->toXml());
      
  4. Certificate Handling (Updated):

    • For PEM certificates, ensure compatibility with OpenSSL:
      $cert = openssl_x509_read(file_get_contents('cert.pem'));
      if ($cert === false) {
          throw new \RuntimeException('Invalid certificate');
      }
      

Extension Points

  1. Custom Bindings (Unchanged): Extend LiteSaml\Binding\AbstractBinding for custom protocols.

  2. Validation Rules (Updated for v5): Override LiteSaml\Validator\AbstractValidator with immutable context:

    use LiteSaml\Context\ImmutableContext;
    
    class CustomValidator extends AbstractValidator {
        public function validate($xml, ImmutableContext $context) {
            // Your logic here
        }
    }
    

3

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