/**
  * @param UserInterface $user
  * @param TokenInterface $token
  * @return UsernamePasswordToken
  */
 protected function doAuthentication(UserInterface $user, TokenInterface $token)
 {
     $auth = (new AuthenticationOperation())->setUsername($user->getUsername())->setPassword($token->getCredentials());
     /** @var AuthenticationResponse $response */
     $response = $this->ldap->getConnection()->execute($auth);
     if (!$response->isAuthenticated()) {
         $this->userChecker->checkLdapErrorCode($user, $response->getErrorCode(), $this->ldap->getConnection()->getConfig()->getLdapType());
         throw new BadCredentialsException($response->getErrorMessage(), $response->getErrorCode());
     }
     $this->dispatcher->dispatch(LdapLoginEvent::SUCCESS, new LdapLoginEvent($user, $token));
     $newToken = new UsernamePasswordToken($user, null, $this->providerKey, $user->getRoles());
     $newToken->setAttributes($token->getAttributes());
     return $newToken;
 }
 /**
  * {@inheritdoc}
  */
 public function checkCredentials($credentials, UserInterface $user)
 {
     $domain = $this->ldap->getDomainContext();
     try {
         $this->switchDomainIfNeeded($credentials);
         /** @var \LdapTools\Operation\AuthenticationResponse $response */
         $response = $this->ldap->getConnection()->execute(new AuthenticationOperation($user->getUsername(), $credentials['password']));
         if (!$response->isAuthenticated()) {
             $this->userChecker->checkLdapErrorCode($user, $response->getErrorCode(), $this->ldap->getConnection()->getConfig()->getLdapType());
             throw new CustomUserMessageAuthenticationException($response->getErrorMessage(), [], $response->getErrorCode());
         }
         // No way to get the token from the Guard, need to create one to pass...
         $token = new UsernamePasswordToken($user, $credentials['password'], 'ldap-tools', $user->getRoles());
         $token->setAttribute('ldap_domain', isset($credentials['ldap_domain']) ? $credentials['ldap_domain'] : '');
         $this->dispatcher->dispatch(LdapLoginEvent::SUCCESS, new LdapLoginEvent($user, $token));
     } catch (\Exception $e) {
         $this->hideOrThrow($e);
     } finally {
         $this->domain = $this->ldap->getDomainContext();
         $this->switchDomainBackIfNeeded($domain);
     }
     return true;
 }