diff --git a/examples/auth_api_key.py b/examples/auth_api_key.py new file mode 100644 index 0000000000000000000000000000000000000000..4db323c1ee48403b27bd6bf56c04eaa5d5ddf555 --- /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 d6a3e06c32fc447e76f6e861321d00439ac1b4cd..398e9f7f602309a9a86301c6d47db68c627bfdeb 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)