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

Ldap Laravel Package

symfony/ldap

Symfony LDAP Component: a PHP LDAP client built on top of the PHP ldap extension. Stable since Symfony 3.1 (earlier versions were internal and may break). Includes docs and contribution resources via the main Symfony repository.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require symfony/ldap
    

    Ensure the php-ldap extension is enabled in your php.ini or Docker container.

  2. Basic Connection Create an LDAP client instance in a Laravel service provider (e.g., AppServiceProvider):

    use Symfony\Component\Ldap\LdapClient;
    
    public function register()
    {
        $this->app->singleton(LdapClient::class, function ($app) {
            return new LdapClient('ldap://your-ldap-server:389');
        });
    }
    
  3. First Use Case: User Authentication Bind a user to verify credentials:

    use Symfony\Component\Ldap\Entry;
    
    $ldap = $this->app->make(LdapClient::class);
    $userDn = 'uid=john.doe,ou=users,dc=example,dc=com';
    $password = 'securePassword123';
    
    try {
        $ldap->bind($userDn, $password);
        // Authentication successful
    } catch (\Symfony\Component\Ldap\Exception\ConnectionException $e) {
        // Handle authentication failure
    }
    
  4. Search for Users Query LDAP for user entries:

    $query = new \Symfony\Component\Ldap\Query();
    $query->where('objectClass')->equals('person');
    $query->where('uid')->equals('john.doe');
    
    $results = $ldap->search($query);
    $entries = $results->toArray();
    

Implementation Patterns

Core Workflows

1. Authentication Workflow

  • Bind with Credentials:
    $ldap->bind($userDn, $password);
    
  • Anonymous Bind (for searches):
    $ldap->bind();
    
  • SASL Bind (for modern LDAP servers):
    $ldap->bind($userDn, null, ['SASL_MECHANISM' => 'GSSAPI']);
    

2. User Provisioning

  • Create a User Entry:
    $entry = Entry::fromData(
        'uid=john.doe,ou=users,dc=example,dc=com',
        [
            'cn' => ['John Doe'],
            'sn' => ['Doe'],
            'mail' => ['john.doe@example.com'],
            'objectClass' => ['top', 'person', 'organizationalPerson'],
        ]
    );
    $ldap->update($entry);
    

3. Group Management

  • Add User to a Group:
    $groupDn = 'cn=developers,ou=groups,dc=example,dc=com';
    $ldap->modify($groupDn, [
        'member' => [
            'uid=john.doe,ou=users,dc=example,dc=com',
            'uid=jane.smith,ou=users,dc=example,dc=com',
        ],
    ]);
    

4. Search with Filters

  • Complex Queries:
    $query = new Query();
    $query->where('memberOf')->equals('cn=admins,ou=groups,dc=example,dc=com');
    $query->where('objectClass')->equals('person');
    
    $results = $ldap->search($query);
    

5. Integration with Laravel Auth

  • Custom User Provider:
    use Illuminate\Contracts\Auth\Authenticatable;
    use Symfony\Component\Ldap\Entry;
    
    class LdapUserProvider implements Authenticatable
    {
        public function retrieveById($identifier)
        {
            // Fetch user from LDAP
        }
    
        public function retrieveByCredentials(array $credentials)
        {
            $ldap = app(LdapClient::class);
            $userDn = $credentials['username'];
            $ldap->bind($userDn, $credentials['password']);
            return $this->createModelFromEntry($ldap->search(new Query()->where('dn')->equals($userDn))->first());
        }
    }
    

Integration Tips

Laravel Service Container

  • Bind LDAP Client:
    $this->app->bind(LdapClient::class, function ($app) {
        $config = config('ldap');
        return new LdapClient(
            $config['host'],
            $config['port'] ?? 389,
            [
                'options' => [
                    'protocol_version' => $config['protocol_version'] ?? 3,
                    'referrals' => $config['follow_referrals'] ?? false,
                ],
            ]
        );
    });
    

Configuration

  • config/ldap.php:
    return [
        'host' => env('LDAP_HOST', 'ldap.example.com'),
        'port' => env('LDAP_PORT', 389),
        'base_dn' => env('LDAP_BASE_DN', 'dc=example,dc=com'),
        'username' => env('LDAP_BIND_DN', 'cn=admin,dc=example,dc=com'),
        'password' => env('LDAP_BIND_PASSWORD', ''),
        'protocol_version' => 3,
        'follow_referrals' => false,
    ];
    

Caching

  • Cache LDAP Results:
    $cacheKey = 'ldap_users_' . md5($query->getQuery());
    $results = Cache::remember($cacheKey, now()->addHours(1), function () use ($ldap, $query) {
        return $ldap->search($query);
    });
    

Error Handling

  • Global Exception Handling:
    try {
        $ldap->search($query);
    } catch (\Symfony\Component\Ldap\Exception\ConnectionException $e) {
        Log::error('LDAP connection failed: ' . $e->getMessage());
        throw new \RuntimeException('LDAP service unavailable');
    }
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts

    • Issue: LDAP operations may hang if the server is slow or unreachable.
    • Fix: Set a timeout in the adapter options:
      $ldap = new LdapClient('ldap://example.com', [
          'options' => [
              'default_socket_timeout' => 5, // 5 seconds
          ],
      ]);
      
  2. Referrals

    • Issue: LDAP servers may return referrals, which can cause infinite loops.
    • Fix: Disable referrals in the adapter:
      $ldap = new LdapClient('ldap://example.com', [
          'options' => [
              'referrals' => false,
          ],
      ]);
      
  3. Schema Mismatches

    • Issue: Querying attributes that don’t exist in the LDAP schema.
    • Fix: Use Entry::getAttribute() with a fallback:
      $email = $entry->getAttribute('mail')[0] ?? null;
      
  4. Case Sensitivity in DN

    • Issue: LDAP DNs are case-insensitive, but some servers enforce case sensitivity.
    • Fix: Normalize DNs before use:
      $normalizedDn = strtolower($userDn);
      
  5. Memory Leaks with Large Results

    • Issue: Fetching large result sets can consume excessive memory.
    • Fix: Use Ldap\Result::toIterator() to stream results:
      foreach ($results->toIterator() as $entry) {
          // Process entry
      }
      

Debugging Tips

  1. Enable LDAP Debugging

    • Set the LDAP_DEBUG environment variable:
      export LDAP_DEBUG=1
      
    • Or enable it programmatically:
      ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
      
  2. Log Raw LDAP Responses

    • Use a custom adapter to log queries:
      $adapter = new \Symfony\Component\Ldap\Adapter\ExtLdapAdapter();
      $adapter->setLogger(new \Monolog\Logger('ldap'));
      $ldap = new LdapClient('ldap://example.com', ['adapter' => $adapter]);
      
  3. Validate LDAP Filters

    • Use the ldap_escape function to sanitize inputs:
      $safeUsername = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
      $query->where('uid')->equals($safeUsername);
      

Extension Points

  1. Custom Entry Mappers
    • Transform LDAP entries into Eloquent models:
      class LdapUserMapper
      {
          public function mapToModel(Entry $
      
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.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata