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

Schemas Laravel Package

litesaml/schemas

Provides XML schemas for the Lite SAML ecosystem, enabling validation and tooling for SAML documents used across Lite Saml packages. Requires PHP 8.1+ and installs via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require litesaml/schemas
    

    Ensure your Laravel project uses PHP 8.1+ (check via php artisan --version).

  2. First Use Case: Validate a SAML Message

    use LiteSAML\Schemas\Schemas;
    
    // Initialize the schemas provider
    $schemas = new Schemas();
    
    // Example SAML AuthnRequest XML (replace with your actual XML)
    $samlXml = '<AuthnRequest xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ...>';
    
    // Validate against the AuthnRequest schema
    $isValid = $schemas->validateSchema('AuthnRequest', $samlXml);
    
    if (!$isValid) {
        // Handle validation error (e.g., log or throw exception)
        throw new \InvalidArgumentException('Invalid SAML AuthnRequest');
    }
    
  3. Where to Look First:

    • Core Class: LiteSAML\Schemas\Schemas (handles schema retrieval and validation).
    • Schema Files: Located in vendor/litesaml/schemas/resources/schemas/ (e.g., AuthnRequest.xsd).
    • Cookbook: LiteSAML Cookbook for advanced use cases.

Implementation Patterns

1. Schema Validation in Laravel Controllers

Integrate validation into a Laravel controller handling SAML requests:

use Illuminate\Http\Request;
use LiteSAML\Schemas\Schemas;

class SamlController extends Controller
{
    protected $schemas;

    public function __construct(Schemas $schemas)
    {
        $this->schemas = $schemas;
    }

    public function handleAuthnRequest(Request $request)
    {
        $samlXml = $request->input('SAMLRequest'); // Base64-decoded XML
        $isValid = $this->schemas->validateSchema('AuthnRequest', $samlXml);

        if (!$isValid) {
            return response()->json(['error' => 'Invalid SAML AuthnRequest'], 400);
        }

        // Proceed with SAML processing
    }
}

2. Service Provider Integration

Register the Schemas class as a Laravel service provider for dependency injection:

// app/Providers/AppServiceProvider.php
use Illuminate\Support\ServiceProvider;
use LiteSAML\Schemas\Schemas;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(Schemas::class, function ($app) {
            return new Schemas();
        });
    }
}

Now inject Schemas into any class via constructor injection.

3. Middleware for SAML Validation

Create middleware to validate SAML messages before processing:

// app/Http/Middleware/ValidateSamlSchema.php
use Closure;
use LiteSAML\Schemas\Schemas;

class ValidateSamlSchema
{
    protected $schemas;

    public function __construct(Schemas $schemas)
    {
        $this->schemas = $schemas;
    }

    public function handle($request, Closure $next)
    {
        if ($request->has('SAMLRequest')) {
            $samlXml = $request->input('SAMLRequest');
            $schemaName = $this->determineSchemaName($request); // Logic to pick schema (e.g., 'AuthnRequest')

            if (!$this->schemas->validateSchema($schemaName, $samlXml)) {
                return response()->json(['error' => 'Invalid SAML schema'], 400);
            }
        }

        return $next($request);
    }
}

Register the middleware in app/Http/Kernel.php.

4. Dynamic Schema Loading

Load schemas dynamically based on runtime conditions (e.g., SAML version):

$schemaName = $request->input('SAMLVersion') === '2.0' ? 'AuthnRequest' : 'AuthnRequest11';
$isValid = $schemas->validateSchema($schemaName, $samlXml);

5. Testing SAML Validation

Use Laravel’s testing tools to validate SAML schemas:

// tests/Feature/SamlValidationTest.php
use Tests\TestCase;
use LiteSAML\Schemas\Schemas;

class SamlValidationTest extends TestCase
{
    public function testValidAuthnRequest()
    {
        $schemas = new Schemas();
        $validXml = file_get_contents(__DIR__ . '/data/valid-authnrequest.xml');
        $this->assertTrue($schemas->validateSchema('AuthnRequest', $validXml));
    }

    public function testInvalidAuthnRequest()
    {
        $schemas = new Schemas();
        $invalidXml = file_get_contents(__DIR__ . '/data/invalid-authnrequest.xml');
        $this->assertFalse($schemas->validateSchema('AuthnRequest', $invalidXml));
    }
}

6. Integration with LiteSAML Core

If using litesaml/core, combine schema validation with SAML processing:

use LiteSAML\Schemas\Schemas;
use LiteSAML\AuthnRequest;

$schemas = new Schemas();
$samlXml = $request->input('SAMLRequest');

// Validate schema first
if (!$schemas->validateSchema('AuthnRequest', $samlXml)) {
    abort(400, 'Invalid SAML AuthnRequest');
}

// Process with LiteSAML
$authnRequest = AuthnRequest::fromString($samlXml);

Gotchas and Tips

Pitfalls

  1. Empty XML Handling:

    • The package throws an error if XML is empty (fixed in v3.1.1). Always sanitize input:
      if (empty($samlXml)) {
          throw new \InvalidArgumentException('SAML XML cannot be empty');
      }
      
  2. Schema Name Mismatches:

    • Incorrect schema names (e.g., AuthnRequest vs. AuthnRequest11) will fail silently. Use exact names from the LiteSAML Cookbook.
  3. XML Encoding Issues:

    • SAML XML must be UTF-8 encoded. Decode base64 properly:
      $samlXml = base64_decode($request->input('SAMLRequest'));
      
  4. Performance with Large XML:

    • Validating large SAML responses (e.g., >1MB) may time out. Optimize with:
      • Streaming XML parsers (e.g., SimpleXML with libxml_disable_entity_loader).
      • Caching validated schemas in Laravel’s cache:
        $schema = Cache::remember("schema_{$schemaName}", 3600, function () use ($schemas, $schemaName) {
            return $schemas->getSchema($schemaName);
        });
        
  5. PHP Extensions:

    • Ensure ext-dom and ext-simplexml are enabled (required for XML validation).

Debugging Tips

  1. Enable XML Error Reporting:

    libxml_use_internal_errors(true);
    $schemas->validateSchema('AuthnRequest', $samlXml);
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        error_log("XML Error: {$error->message} (Line {$error->line})");
    }
    libxml_clear_errors();
    
  2. Log Schema Validation Failures:

    try {
        $isValid = $schemas->validateSchema('AuthnRequest', $samlXml);
    } catch (\Exception $e) {
        \Log::error("SAML Validation Failed", [
            'schema' => 'AuthnRequest',
            'error' => $e->getMessage(),
            'xml_sample' => substr($samlXml, 0, 500) // Log first 500 chars
        ]);
    }
    
  3. Validate Against Test Vectors: Use OASIS SAML Test Vectors to test edge cases.

Configuration Quirks

  1. Schema Path Customization: Override the default schema directory (e.g., for custom schemas):

    $schemas = new Schemas();
    $schemas->setSchemaDirectory(__DIR__ . '/custom-schemas');
    
  2. Laravel Caching: Cache schema objects to avoid repeated file reads:

    $schema = Cache::remember("schema_{$schemaName}", now()->addHours(1), function () use ($schemas, $schemaName) {
        return $schemas->getSchema($schemaName);
    });
    
  3. SAML Version Handling:

    • SAML 1.1 and 2.0 schemas are separate. Use `
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.
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
spatie/mailcoach-vapor