# LDAP

> LDAP directories for Yii2 through native LdapRecord models

Package entry: `yii2-extensions/ldap`. Requires PHP `~8.3.25 || >=8.4.12`, Yii2 `~2.0.55 || ^22.0@dev`. Checked 2026-11-30. [View the entry in the package directory](</docs/packages/yii2-extensions/ldap/index.md>)

**LDAP directories for Yii2 through native LdapRecord models**

_Named connections, user synchronization, group membership, and optional password verification_

## Features

![Feature Overview](https://raw.githubusercontent.com/yii2-extensions/ldap/main/docs/svgs/features.svg)

## Quick start

### Installation

The package needs the PHP LDAP extension in the runtime that serves the application, not only in the CLI. Install it
with Composer:

```bash
composer require yii2-extensions/ldap:^0.1
```

Applications on Yii 2.0 need a Bower asset source such as Asset Packagist. The
[Installation Guide](https://github.com/yii2-extensions/ldap/blob/main/docs/installation.md) covers it, together with
Yii 22 and local checkouts.

### Usage

One directory, two service accounts. `people` binds a read-only account for queries and synchronization; `memberships`
binds a separate account whose LDAP ACL allows it to modify group members. The password verifier is optional and shares
nothing with either of them.

```php
use yii2\extensions\ldap\Directory;
use yii2\extensions\ldap\PasswordVerifier;

return [
    // Registers the named connections with LdapRecord at bootstrap. No socket opens until the first query.
    'bootstrap' => ['directory'],
    'components' => [
        'directory' => [
            'class' => Directory::class,
            'connections' => [
                'people' => [
                    'host' => 'directory.example.org',
                    'baseDn' => 'dc=example,dc=org',
                    'username' => 'cn=reader,ou=services,dc=example,dc=org',
                    'password' => getenv('APP_LDAP_READ_PASSWORD'),
                ],
                'memberships' => [
                    'host' => 'directory.example.org',
                    'baseDn' => 'dc=example,dc=org',
                    'username' => 'cn=writer,ou=services,dc=example,dc=org',
                    'password' => getenv('APP_LDAP_WRITE_PASSWORD'),
                    // Opts this name into setMembership(). Synchronization refuses it.
                    'writable' => true,
                ],
            ],
        ],
        // Only when the application itself checks LDAP passwords. Skip it behind Keycloak or another SSO.
        'ldapLogin' => [
            'class' => PasswordVerifier::class,
            'host' => 'directory.example.org',
        ],
    ],
];
```

Every connection upgrades to StartTLS and validates the server certificate before it sends a credential. There is no
plaintext fallback and referrals are not followed.

```php
use LdapRecord\Models\OpenLDAP\{Group, User};
use yii2\extensions\ldap\{Directory, DirectoryUnavailableException, PasswordVerifier, UserSynchronizer};

/** @var Directory $directory */
$directory = Yii::$app->get('directory');

// Native LdapRecord models. The connection name selects the directory and the account that reads it.
$alex = User::on('people')
    ->whereEquals('uid', 'alex')
    ->firstOrFail();

$groups = $alex->groups()->get();

// Copy two attributes into a local table, page by page, on a connection isolated from other queries.
// Each row is keyed by the connection name and the entryUUID (objectGUID on Active Directory), never by
// username or DN. A page that fails stops the run instead of passing for a complete directory.
$count = (new UserSynchronizer($directory))->sync(
    User::on('people'),
    ['display_name' => 'cn', 'email' => 'mail'],
    static function (string $source, string $guid, array $attributes): void {
        // Values arrive as LdapRecord returns them: a list per attribute, or null when the entry has none.
        $profile = [
            'display_name' => $attributes['display_name'][0] ?? null,
            'email' => $attributes['email'][0] ?? null,
        ];

        Yii::$app->db->createCommand()->upsert(
            '{{%directory_user}}',
            ['ldap_source' => $source, 'ldap_guid' => $guid] + $profile,
            $profile,
        )->execute();
    },
);

// One direct membership, one LDAP modify. Both models must be loaded on the writable connection:
// a group or user loaded on `people` is refused with InvalidConfigException before anything is sent.
$operators = Group::on('memberships')->whereEquals('cn', 'operators')->firstOrFail();
$member = User::on('memberships')->whereEquals('uid', 'alex')->firstOrFail();

$directory->setMembership($operators, $member, true);
$directory->setMembership($operators, $member, false);

// Optional password check for an identity the application already resolved. One call, three outcomes:
// true, false for a rejected password, or an exception when the directory cannot give an answer.
/** @var PasswordVerifier $verifier */
$verifier = Yii::$app->get('ldapLogin');

try {
    $valid = $verifier->verify($identity->ldapPrincipal, $password);
} catch (DirectoryUnavailableException) {
    $valid = false;
}
```

`$identity->ldapPrincipal` is the bind name the application stores for that user; never take it from the request. The
[Usage Examples](https://github.com/yii2-extensions/ldap/blob/main/docs/examples.md) add queries across two directories
and the full login flow. The
[Configuration Guide](https://github.com/yii2-extensions/ldap/blob/main/docs/configuration.md) details certificate
trust, least-privilege accounts and persistent workers.

## Documentation

Practical guides for connecting directories, querying native models, and running the test suite.

- 📚 [Installation Guide](https://github.com/yii2-extensions/ldap/blob/main/docs/installation.md)
- ⚙️ [Configuration Guide](https://github.com/yii2-extensions/ldap/blob/main/docs/configuration.md)
- 💡 [Usage Examples](https://github.com/yii2-extensions/ldap/blob/main/docs/examples.md)
- 🤖 [AI Agents Guide](https://github.com/yii2-extensions/ldap/blob/main/docs/agents.md)
- 🧪 [Testing Guide](https://github.com/yii2-extensions/ldap/blob/main/docs/testing.md)

The guides and the [API reference](https://yii2-framework.github.io/docs/extensions/ldap/reference/) generated from the
PHPDoc in `src/` are published at <https://yii2-framework.github.io/docs/extensions/ldap/>.

## AI assistance

AI agents: read the [documentation index](https://yii2-framework.github.io/docs/llms.txt) and fetch the Markdown version
of a page by appending `index.md` to its URL. The
[AI agents guide](https://yii2-framework.github.io/docs/project/ai-agents/) covers skill installation, client setup and
verification.

- 🤖 [`yii2-ldap` skill](https://github.com/yii2-extensions/ldap/blob/main/docs/agents.md): named LDAP connections, user
  synchronization, direct group membership, and optional password verification.
- 🧭 [`yii2-framework` skill](https://yii2-framework.github.io/docs/guide/skills/yii2-framework/): Yii 22.0 application
  conventions.

The hosted documentation covers Yii 22.0. If it does not match the installed revision or is unavailable, use the
[repository guides](#documentation), the [skill source](https://github.com/yii2-extensions/ldap/blob/main/skills/yii2-ldap/SKILL.md), the source PHPDoc and the
[changelog](https://github.com/yii2-extensions/ldap/blob/main/CHANGELOG.md).

## Our social networks

[Follow on X](https://x.com/Terabytesoftw)
[Follow on Facebook](https://www.facebook.com/wilmer.arambula.9)
[Join our Subreddit](https://www.reddit.com/r/Yii2/)
[Join on Telegram](https://t.me/yii_framework_in_english)

## License

[License](https://github.com/yii2-extensions/ldap/blob/main/LICENSE)

## Package

- Source code and issues: [yii2-extensions/ldap](https://github.com/yii2-extensions/ldap). Star the repository if the package is useful to you.
- Composer package: [yii2-extensions/ldap](https://packagist.org/packages/yii2-extensions/ldap).
- Changelog: [CHANGELOG.md](https://github.com/yii2-extensions/ldap/blob/main/CHANGELOG.md).