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

Xml Security Laravel Package

simplesamlphp/xml-security

Secure, extensible XML signature and encryption library for PHP (xmldsig/xmlenc). Built on simplesamlphp/xml-common, it helps you sign/verify and encrypt/decrypt XML objects via high-level interfaces, with lower-level APIs available when needed.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the package via Composer (ensure PHP 8.0+ with OpenSSL):
   ```bash
   composer require simplesamlphp/xml-security:^2.0

Note: v2.0 enforces stricter XSD-type validation. Ensure your XML schema aligns with W3C standards.

  1. First Use Case: Signing XML (Updated for v2.0)

    use SimpleSAML\XML\Security\XMLSecurityKey;
    use SimpleSAML\XML\Security\XMLSecurityDSig;
    
    // Generate/load key (PEM format required)
    $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, ['type' => 'private']);
    $key->loadKey(file_get_contents(storage_path('app/keys/saml_private.pem')), true);
    
    // Initialize with strict XSD validation (v2.0 default)
    $objDSig = new XMLSecurityDSig($key, XMLSecurityDSig::ELEMENT | XMLSecurityDSig::EXCL_C14N);
    $objDSig->setCanonicalizationMethod(XMLSecurityDSig::EXCL_C14N); // Explicit for clarity
    
    // Sign with XSD-aware reference
    $objDSig->addReference(
        '//*[local-name()="Assertion"]',
        XMLSecurityDSig::EXCL_C14N,
        ['http://www.w3.org/2001/10/xml-excl-c14n#'],
        ['http://www.w3.org/2000/09/xmldsig#sha256']
    );
    $objDSig->appendSignatureToNode($xmlDoc->documentElement);
    $signedXml = $objDSig->sign($key);
    
  2. Key Resources


Implementation Patterns

Common Workflows (v2.0)

  1. SAML Assertion Signing with XSD Validation

    // Load SAML response (ensure it validates against XSD)
    $samlXml = simplexml_load_string($samlResponse);
    libxml_clear_errors(); // Reset before validation
    $validator = new \DOMDocument();
    $validator->loadXML($samlResponse);
    if ($validator->schemaValidate('saml-schema-provider.xsd')) {
        // Proceed with signing
        $key = $this->samlKeyManager->getPrivateKey();
        $objDSig = new XMLSecurityDSig($key, XMLSecurityDSig::ELEMENT);
        $objDSig->addReference('//*[local-name()="Assertion"]', XMLSecurityDSig::EXCL_C14N);
        $objDSig->appendSignatureToNode($samlXml->xpath('//*[local-name()="Response"]')[0]);
    } else {
        throw new \InvalidArgumentException("SAML response fails XSD validation");
    }
    
  2. Verifying Signatures with Strict XSD Checks

    $objDSig = new XMLSecurityDSig();
    $objDSig->idKeys = true;
    $objDSig->setStrictXsdValidation(true); // v2.0 feature
    
    // Validate XML structure before verification
    $xmlDoc = new \DOMDocument();
    $xmlDoc->loadXML($samlResponse);
    if (!$xmlDoc->schemaValidate('saml-schema-provider.xsd')) {
        throw new \RuntimeException("Invalid SAML structure");
    }
    
    $verified = $objDSig->verify($xmlDoc);
    if (!$verified) {
        throw new \RuntimeException("Signature verification failed (XSD mismatch?)");
    }
    
  3. Key Management (v2.0 Compliance)

    • Key Generation: Use OpenSSL v3.0+ for RSA keys with explicit XSD-compliant headers:
      openssl genpkey -algorithm RSA -out saml_private.pem -pkeyopt rsa_keygen_bits:2048
      openssl rsa -pubout -in saml_private.pem -out saml_public.pem
      
    • Laravel Config:
      'saml' => [
          'key_paths' => [
              'private' => storage_path('app/keys/saml_private.pem'),
              'public'  => storage_path('app/keys/saml_public.pem'),
          ],
          'xsd_schema' => resource_path('schemas/saml-schema-provider.xsd'),
      ],
      
  4. Integration with Laravel HTTP (v2.0)

    // Middleware with XSD pre-validation
    public function handle($request, Closure $next) {
        $xml = simplexml_load_string($request->getContent());
        $validator = new \DOMDocument();
        $validator->loadXML($request->getContent());
        if (!$validator->schemaValidate(config('saml.xsd_schema'))) {
            abort(400, "Invalid SAML structure");
        }
        $this->verifySignature($xml);
        return $next($request);
    }
    

Best Practices (v2.0)

  • XSD Schema: Always validate against the SAML 2.0 Provider Schema before signing/verifying.
  • Key Algorithms: Prefer RSA_SHA256 or RSA_SHA512 for XSD compliance.
  • Error Handling: Catch XMLSecurityException for type mismatches:
    try {
        $objDSig->sign($key);
    } catch (\SimpleSAML\XML\Security\XMLSecurityException $e) {
        Log::error("XSD validation failed: " . $e->getMessage());
        throw new \RuntimeException("Invalid XML structure");
    }
    

Gotchas and Tips

Pitfalls (v2.0)

  1. XSD Validation Failures

    • Symptoms: Signing/verification silently fails or throws XMLSecurityException.
    • Causes:
      • Missing ID attributes on signed elements.
      • Incorrect namespace prefixes (e.g., ds: vs xmlns:ds).
      • Non-compliant XML structure (e.g., missing Issuer in SAML).
    • Fix:
      // Enable strict XSD error reporting
      $objDSig->setStrictXsdValidation(true);
      $objDSig->debug = true; // Logs XSD validation steps
      
  2. Key Format Strictness

    • v2.0 rejects keys without proper PEM headers or with malformed XSD types.
    • Fix: Regenerate keys with:
      openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in old_key.pem -out new_key.pem
      
  3. Canonicalization Mismatches

    • v2.0 defaults to EXCL_C14N but may reject non-compliant XML.
    • Debug: Compare canonicalized output:
      $c14n = new XMLSecurityC14N(true, 'http://www.w3.org/2001/10/xml-excl-c14n#');
      $canonicalized = $c14n->canonicalize($xmlDoc);
      
  4. Performance with Large XML

    • v2.0’s strict XSD checks add overhead. For documents >5MB:
      • Use XMLSecurityDSig::DETACHED mode.
      • Pre-validate XML with DOMDocument::schemaValidate().

Debugging Tips (v2.0)

  • XSD Validation Logs:
    $validator = new \DOMDocument();
    $validator->validationErrorHandler = function($err) {
        Log::error("XSD Error: " . $err->getMessage());
    };
    $validator->loadXML($xml);
    
  • Key Type Inspection:
    $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256);
    if (!$key->type === XMLSecurityKey::RSA_SHA256) {
        throw new \RuntimeException("Unsupported key type");
    }
    
  • Signature Debugging:
    $objDSig->debugOutput = true; // Logs to stderr
    $objDSig->debug = true;       // Includes XSD validation steps
    

Extension Points (v2.0)

  1. Custom XSD Validator Override default validation with a Laravel service:
    class SamlXsdValidator {
        public function validate(string $xml): bool {
            $validator = new \DOMDocument();
            $validator->loadXML($xml);
            return $validator->schemaValidate(resource_path('schemas
    
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