Skip to content

Commit 5673bbe

Browse files
committed
ApiKey authentication and ess best practises headers
1 parent e201997 commit 5673bbe

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/Elasticsearch/ClientBuilder.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,11 @@ class ClientBuilder
126126
*/
127127
private $sslVerification = null;
128128

129+
/**
130+
* @var null|string
131+
*/
132+
private $apiKey = null;
133+
129134
public static function create(): ClientBuilder
130135
{
131136
return new static();
@@ -330,13 +335,64 @@ public function setHosts(array $hosts): ClientBuilder
330335
return $this;
331336
}
332337

338+
/**
339+
* Set the APIKey for Authenication
340+
*
341+
* @link https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html
342+
*
343+
* @param string $apiKey
344+
*/
345+
public function setApiKeyAuthentication(string $apiKey)
346+
{
347+
$this->connectionParams['client']['headers']['Authorization'] = ['ApiKey ' . $apiKey];
348+
349+
return $this;
350+
}
351+
352+
/**
353+
* Set the APIKey Pair, consiting of the API Id and the ApiKey of the Response from /_security/api_key
354+
*
355+
* @link https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html
356+
*
357+
* @param string $id
358+
* @param string $apiKey
359+
*/
360+
public function setApiKeyPairAuthentication(string $id, string $apiKey)
361+
{
362+
$this->setApiKeyAuthentication(base64_encode($id . ':' . $apiKey));
363+
364+
return $this;
365+
}
366+
333367
public function setConnectionParams(array $params): ClientBuilder
334368
{
335369
$this->connectionParams = $params;
336370

337371
return $this;
338372
}
339373

374+
/**
375+
* Set Elastic Cloud's best Practices Connection Parameters
376+
*
377+
* <i>Add custom/additional Params as parameter</i>
378+
*
379+
* @param array $additional
380+
*/
381+
public function setElasticCloudConnectionParams(array $additional = [])
382+
{
383+
$this->setConnectionParams(
384+
[
385+
'client' => [
386+
'curl' => [
387+
CURLOPT_ENCODING => 1,
388+
],
389+
]
390+
] + $additional
391+
);
392+
393+
return $this;
394+
}
395+
340396
public function setRetries(int $retries): ClientBuilder
341397
{
342398
$this->retries = $retries;
@@ -565,6 +621,7 @@ private function buildConnectionsFromHosts(array $hosts): array
565621
$this->logger->error("Could not parse host: ".print_r($host, true));
566622
throw new RuntimeException("Could not parse host: ".print_r($host, true));
567623
}
624+
568625
$connections[] = $this->connectionFactory->create($host);
569626
}
570627

0 commit comments

Comments
 (0)