From eb0e5fe843b3a1809a17c0fdacd85a32aacf3fd6 Mon Sep 17 00:00:00 2001 From: Georgiy Eterevskiy <goshik_e@mail.ru> Date: Mon, 7 Feb 2022 18:36:33 +0300 Subject: [PATCH] Add plugin `Api-Key` for auth --- examples/auth_api_key.py | 29 +++++++++++++++++++++++++++++ perxis/auth.py | 13 +++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 examples/auth_api_key.py diff --git a/examples/auth_api_key.py b/examples/auth_api_key.py new file mode 100644 index 0000000..4db323c --- /dev/null +++ b/examples/auth_api_key.py @@ -0,0 +1,29 @@ +import logging + +import grpc + +from perxis.auth import APIKeyPlugin +from perxis.collections import collections_pb2_grpc, collections_pb2 + +API_KEY = '0Xp7bYBqYmIUqwZcNRMtRCtDBaheFdAc' +SPACE_ID = 'c2qcp9cuaccmpj8lmom0' +ENV_ID = 'master' +TARGET = 'envoy.perxis.pt.perx.ru:443' + + +def main(): + api_key_plugin = APIKeyPlugin(API_KEY) + call_credentials = grpc.metadata_call_credentials(api_key_plugin, name='api-key') + channel_credentials = grpc.ssl_channel_credentials() + composite_credentials = grpc.composite_channel_credentials( + channel_credentials, call_credentials + ) + with grpc.secure_channel(TARGET, composite_credentials) as channel: + stub = collections_pb2_grpc.CollectionsStub(channel) + collections = stub.List(collections_pb2.ListRequest(space_id=SPACE_ID, env_id=ENV_ID)) + print(collections) + + +if __name__ == '__main__': + logging.basicConfig(level=logging.INFO) + main() diff --git a/perxis/auth.py b/perxis/auth.py index d6a3e06..398e9f7 100644 --- a/perxis/auth.py +++ b/perxis/auth.py @@ -50,3 +50,16 @@ class OAuth2Plugin(grpc.AuthMetadataPlugin): self._token = fetch_token() return self._token + + +class APIKeyPlugin(grpc.AuthMetadataPlugin): + _token = None + + def __init__(self, token: str, signature_header_key: str = 'authorization', token_type: str = 'API-Key') -> None: + self._token = token + self._signature_header_key = signature_header_key + self._token_type = token_type + + def __call__(self, context: grpc.AuthMetadataContext, + callback: grpc.AuthMetadataPluginCallback) -> None: + callback(((self._signature_header_key, f'{self._token_type} {self._token}'),), None) -- GitLab