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

Onelogin Azure Saml Bundle Laravel Package

anglemx/onelogin-azure-saml-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup for Azure AD SAML Integration
1. **Install the Bundle**
   ```bash
   composer require anglemx/onelogin-azure-saml-bundle

Enable in config/bundles.php:

Angle\OneLoginAzureSamlBundle\AngleOneLoginAzureSamlBundle::class => ['all' => true],
  1. Configure Azure AD Credentials Add to config/packages/angle_one_login_azure_saml.yaml:

    angle_one_login_azure_saml:
        azure_app_id: 'your-azure-app-guid-here'
        azure_x509_cert: '-----BEGIN CERTIFICATE-----\n...Azure AD cert...\n-----END CERTIFICATE-----'
        app_base_url: 'https://your-app.com'  # No trailing slash
    
  2. Generate SP Metadata Run the built-in command to auto-generate SP settings:

    php bin/console angle:onelogin:azure:saml:metadata
    

    This outputs the EntityID and other SP URLs (e.g., https://your-app.com/sp).

  3. Configure Azure AD App Registration

    • Register an app in Azure Portal with:
      • Reply URL: https://your-app.com/saml/acs
      • Sign-on URL: https://your-app.com/saml/login
      • Identifier (Entity ID): https://your-app.com/sp (from the command output).
    • Upload the SP metadata XML (exported from https://your-app.com/saml/metadata) to Azure AD.
  4. Secure Routes Update config/packages/security.yaml:

    security:
        providers:
            saml_provider:
                saml:
                    user_class: App\Entity\User
                    default_roles: ['ROLE_USER']
        firewalls:
            main:
                saml:
                    username_attribute: uid  # Azure AD attribute for username
                    use_attribute_friendly_name: false  # CRITICAL for Azure
                    check_path: saml_acs
                    login_path: saml_login
                logout:
                    path: saml_logout
    
  5. Test Locally

    • Access https://your-app.com/saml/login to trigger Azure AD login.
    • Verify user attributes in {{ dump(app.user) }} (Symfony Twig).

Implementation Patterns

1. Dynamic SP Configuration

  • Auto-Generated URLs: The bundle auto-calculates Azure AD-compliant SP URLs (e.g., EntityID, AssertionConsumerService) using azure_app_id and app_base_url. Avoid hardcoding these.
  • Metadata Endpoint: Expose SP metadata at /saml/metadata for Azure AD to consume. Use the command to debug:
    php bin/console angle:onelogin:azure:saml:metadata
    

2. User Attribute Mapping

  • Azure AD Attributes: Map Azure AD claims to Symfony users via username_attribute (e.g., uid, email, name). Example:
    saml:
        username_attribute: user_principal_name  # Azure AD's UPN
    
  • Custom Attributes: Extend the user provider to handle additional claims:
    // src/Security/SamlUserProvider.php
    public function loadUserBySamlAttribute(array $attributes)
    {
        $user = new User();
        $user->setEmail($attributes['email'][0] ?? null);
        $user->setFirstName($attributes['given_name'][0] ?? null);
        return $user;
    }
    

3. Debugging & Logging

  • Enable Debug Mode: Set debug: true in the config to log SAML messages to var/log/saml.log.
  • Error Handling: Use the error event listener to customize error responses:
    # config/packages/security.yaml
    firewalls:
        main:
            saml:
                error_path: saml_error
    
    // src/EventListener/SamlErrorListener.php
    public function onSamlError(SamlEvent $event)
    {
        $event->setResponse(new RedirectResponse('/saml/error?msg=' . $event->getError()));
    }
    

4. Behind Proxies

  • Trust Proxy Headers: If behind a proxy (e.g., Nginx), enable:
    angle_one_login_azure_saml:
        trust_proxy: true  # For Symfony 5.4+
    

5. Custom Routes

  • Override Default Routes: Extend the bundle’s routing in config/routes.yaml:
    saml_login:
        path: /auth/azure
        controller: Angle\OneLoginAzureSamlBundle\Controller\SamlController::login
    

6. Testing

  • Mock Azure AD: Use the onelogin/php-saml library’s test utilities to simulate SAML responses:
    // tests/Functional/SamlTest.php
    use OneLogin\Saml2\Auth;
    
    public function testSamlLogin()
    {
        $auth = new Auth();
        $auth->setSettings($this->getSamlSettings());
        $auth->login(); // Simulate SAML response
    }
    

Gotchas and Tips

Pitfalls

  1. EntityID Mismatch

    • Issue: Azure AD rejects login if the EntityID in the SP metadata doesn’t match the registered app.
    • Fix: Always use the output from php bin/console angle:onelogin:azure:saml:metadata (e.g., https://your-app.com/sp).
  2. use_attribute_friendly_name: false

    • Issue: Azure AD requires this to be false. If set to true, login fails silently.
    • Fix: Explicitly set it in security.yaml:
      saml:
          use_attribute_friendly_name: false
      
  3. Certificate Expiry

    • Issue: Azure AD rotates certificates. If the azure_x509_cert expires, SAML fails.
    • Fix: Monitor Azure AD’s certificate expiry and update the config:
      angle_one_login_azure_saml:
          azure_x509_cert: '-----BEGIN CERTIFICATE-----\n...NEW_CERT...\n-----END CERTIFICATE-----'
      
  4. Private Key Requirements

    • Issue: The SP’s privateKey must be a valid PEM-encoded RSA key. Invalid keys cause metadata generation to fail.
    • Fix: Generate a key pair:
      openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
      openssl rsa -pubout -in private_key.pem -out public_key.pem
      
      Then add the private key to the config.
  5. Base URL Configuration

    • Issue: app_base_url must not include a trailing slash (e.g., https://app.com not https://app.com/).
    • Fix: Validate the URL in a custom validator or use Symfony’s UrlGeneratorInterface.
  6. Debug Mode in Production

    • Issue: Leaving debug: true in production exposes sensitive SAML logs.
    • Fix: Use environment variables:
      angle_one_login_azure_saml:
          debug: '%env(bool:SAML_DEBUG)%'
      
      Then set SAML_DEBUG=false in .env.
  7. Attribute Name Conflicts

    • Issue: Azure AD may return attributes with conflicting names (e.g., name vs. displayName).
    • Fix: Normalize attributes in the user provider:
      $user->setFullName($attributes['name'][0] ?? $attributes['displayName'][0] ?? null);
      

Debugging Tips

  1. Check SAML Logs

    • Logs are written to var/log/saml.log. Enable with:
      angle_one_login_azure_saml:
          debug: true
      
  2. Validate Metadata

  3. Test with Postman

    • Manually trigger SAML flows by sending a POST to /saml/acs with a SAML response (use Azure AD’s test tools to generate one).
  4. Symfony Profiler

    • Enable the profiler to inspect SAML events:
      // config/packages/dev/security.yaml
      firewalls:
          dev:
              pattern: ^/(_(profiler|wdt)|css|images|js)/
              security: false
      

Extension Points

  1. Custom User Provider
    • Extend the default provider to handle custom logic:
      // src/Security/SamlUserProvider.php
      class CustomSamlUserProvider extends SamlUserProvider
      {
          public function loadUserBySaml
      
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle