API key Authentication (#1010)

This commit is contained in:
Philip Krauss
2019-09-20 14:01:31 +01:00
committed by Honza Král
parent dd206ad5c5
commit c4bc2e420d
5 changed files with 72 additions and 0 deletions
+12
View File
@@ -1,4 +1,5 @@
import logging
import base64
from platform import python_version
@@ -183,3 +184,14 @@ class Connection(object):
def _get_default_user_agent(self):
return "elasticsearch-py/%s (Python %s)" % (__versionstr__, python_version())
def _get_api_key_header_val(self, api_key):
"""
Check the type of the passed api_key and return the correct header value
for the `API Key authentication <https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`
:arg api_key, either a tuple or a base64 encoded string
"""
if isinstance(api_key, (tuple, list)):
s = "{0}:{1}".format(api_key[0], api_key[1]).encode('utf-8')
return "ApiKey " + base64.b64encode(s).decode('utf-8')
return "ApiKey " + api_key
@@ -36,6 +36,7 @@ class RequestsHttpConnection(Connection):
separate cert and key files (client_cert will contain only the cert)
:arg headers: any custom http headers to be add to requests
:arg cloud_id: The Cloud ID from ElasticCloud. Convient way to connect to cloud instances.
:arg api_key: optional API Key authentication as either base64 encoded string or a tuple.
Other host connection params will be ignored.
"""
@@ -52,6 +53,7 @@ class RequestsHttpConnection(Connection):
client_key=None,
headers=None,
cloud_id=None,
api_key=None,
**kwargs
):
if not REQUESTS_AVAILABLE:
@@ -80,6 +82,8 @@ class RequestsHttpConnection(Connection):
elif isinstance(http_auth, string_types):
http_auth = tuple(http_auth.split(":", 1))
self.session.auth = http_auth
if api_key is not None:
self.session.headers['authorization'] = self._get_api_key_header_val(api_key)
self.base_url = "http%s://%s:%d%s" % (
"s" if self.use_ssl else "",
host,
+4
View File
@@ -74,6 +74,7 @@ class Urllib3HttpConnection(Connection):
:arg headers: any custom http headers to be add to requests
:arg http_compress: Use gzip compression
:arg cloud_id: The Cloud ID from ElasticCloud. Convient way to connect to cloud instances.
:arg api_key: optional API Key authentication as either base64 encoded string or a tuple.
Other host connection params will be ignored.
"""
@@ -96,6 +97,7 @@ class Urllib3HttpConnection(Connection):
ssl_context=None,
http_compress=False,
cloud_id=None,
api_key=None,
**kwargs
):
@@ -128,6 +130,8 @@ class Urllib3HttpConnection(Connection):
self.headers.setdefault("content-type", "application/json")
self.headers.setdefault("user-agent", self._get_default_user_agent())
if api_key is not None:
self.headers.setdefault('authorization', self._get_api_key_header_val(api_key))
pool_class = urllib3.HTTPConnectionPool
kw = {}