diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php index d2d096c4ba20e..3f757154104c2 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php @@ -18,6 +18,7 @@ use Symfony\Component\Ldap\Exception\ConnectionTimeoutException; use Symfony\Component\Ldap\Exception\InvalidCredentialsException; use Symfony\Component\Ldap\Exception\LdapException; +use Symfony\Component\Ldap\Exception\NotBoundException; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -116,6 +117,10 @@ public function saslBind(?string $dn = null, #[\SensitiveParameter] ?string $pas */ public function whoami(): string { + if (!$this->connection) { + throw new NotBoundException(\sprintf('Cannot execute "%s()" before calling "%s::saslBind()".', __METHOD__, __CLASS__)); + } + if (false === $authzId = ldap_exop_whoami($this->connection)) { throw new LdapException(ldap_error($this->connection)); } diff --git a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php index c436c39045c94..5607cdd437603 100644 --- a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php +++ b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/AdapterTest.php @@ -39,12 +39,39 @@ public function testLdapEscape() */ public function testSaslBind() { + $h = @ldap_connect(getenv('LDAP_HOST'), getenv('LDAP_PORT')); + @ldap_set_option($h, \LDAP_OPT_PROTOCOL_VERSION, 3); + + if (!$h || !@ldap_bind($h)) { + $this->markTestSkipped('No server is listening on LDAP_HOST:LDAP_PORT'); + } + + if (!@ldap_start_tls($h)) { + ldap_unbind($h); + $this->markTestSkipped('Cannot establish an encrypted connection'); + } + + ldap_unbind($h); + $ldap = new Adapter($this->getLdapConfig()); $ldap->getConnection()->saslBind('cn=admin,dc=symfony,dc=com', 'symfony'); $this->assertEquals('cn=admin,dc=symfony,dc=com', $ldap->getConnection()->whoami()); } + /** + * @group functional + */ + public function testWhoamiWithoutSaslBind() + { + $ldap = new Adapter($this->getLdapConfig()); + + $this->expectException(NotBoundException::class); + $this->expectExceptionMessage('Cannot execute "Symfony\Component\Ldap\Adapter\ExtLdap\Connection::whoami()" before calling "Symfony\Component\Ldap\Adapter\ExtLdap\Connection::saslBind()".'); + + $ldap->getConnection()->whoami(); + } + /** * @group functional */