async_customized_auth_client.py
Go to the documentation of this file.
1 # Copyright 2020 The gRPC Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Client of the Python AsyncIO example of customizing authentication mechanism."""
15 
16 import argparse
17 import asyncio
18 import logging
19 
20 import _credentials
21 import grpc
22 
23 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
24  "helloworld.proto")
25 
26 _LOGGER = logging.getLogger(__name__)
27 _LOGGER.setLevel(logging.INFO)
28 
29 _SERVER_ADDR_TEMPLATE = 'localhost:%d'
30 _SIGNATURE_HEADER_KEY = 'x-signature'
31 
32 
34 
35  def __call__(self, context: grpc.AuthMetadataContext,
36  callback: grpc.AuthMetadataPluginCallback) -> None:
37  """Implements authentication by passing metadata to a callback.
38 
39  Implementations of this method must not block.
40 
41  Args:
42  context: An AuthMetadataContext providing information on the RPC that
43  the plugin is being called to authenticate.
44  callback: An AuthMetadataPluginCallback to be invoked either
45  synchronously or asynchronously.
46  """
47  # Example AuthMetadataContext object:
48  # AuthMetadataContext(
49  # service_url=u'https://localhost:50051/helloworld.Greeter',
50  # method_name=u'SayHello')
51  signature = context.method_name[::-1]
52  callback(((_SIGNATURE_HEADER_KEY, signature),), None)
53 
54 
56  # Call credential object will be invoked for every single RPC
57  call_credentials = grpc.metadata_call_credentials(AuthGateway(),
58  name='auth gateway')
59  # Channel credential will be valid for the entire channel
60  channel_credential = grpc.ssl_channel_credentials(
61  _credentials.ROOT_CERTIFICATE)
62  # Combining channel credentials and call credentials together
63  composite_credentials = grpc.composite_channel_credentials(
64  channel_credential,
65  call_credentials,
66  )
67  channel = grpc.aio.secure_channel(addr, composite_credentials)
68  return channel
69 
70 
71 async def send_rpc(channel: grpc.aio.Channel) -> helloworld_pb2.HelloReply:
72  stub = helloworld_pb2_grpc.GreeterStub(channel)
73  request = helloworld_pb2.HelloRequest(name='you')
74  try:
75  response = await stub.SayHello(request)
76  except grpc.RpcError as rpc_error:
77  _LOGGER.error('Received error: %s', rpc_error)
78  return rpc_error
79  else:
80  _LOGGER.info('Received message: %s', response)
81  return response
82 
83 
84 async def main() -> None:
85  parser = argparse.ArgumentParser()
86  parser.add_argument('--port',
87  nargs='?',
88  type=int,
89  default=50051,
90  help='the address of server')
91  args = parser.parse_args()
92 
93  channel = create_client_channel(_SERVER_ADDR_TEMPLATE % args.port)
94  await send_rpc(channel)
95  await channel.close()
96 
97 
98 if __name__ == '__main__':
99  logging.basicConfig(level=logging.INFO)
100  asyncio.run(main())
helloworld_pb2_grpc.GreeterStub
Definition: helloworld/helloworld_pb2_grpc.py:7
grpc.aio._base_channel.Channel
Definition: _base_channel.py:184
async_customized_auth_client.AuthGateway.__call__
None __call__(self, grpc.AuthMetadataContext context, grpc.AuthMetadataPluginCallback callback)
Definition: async_customized_auth_client.py:35
helloworld_pb2.HelloRequest
HelloRequest
Definition: helloworld/helloworld_pb2.py:93
grpc.AuthMetadataPlugin
Definition: src/python/grpcio/grpc/__init__.py:617
async_customized_auth_client.create_client_channel
grpc.aio.Channel create_client_channel(str addr)
Definition: async_customized_auth_client.py:55
grpc.RpcError
Definition: src/python/grpcio/grpc/__init__.py:302
grpc.composite_channel_credentials
def composite_channel_credentials(channel_credentials, *call_credentials)
Definition: src/python/grpcio/grpc/__init__.py:1691
grpc.metadata_call_credentials
def metadata_call_credentials(metadata_plugin, name=None)
Definition: src/python/grpcio/grpc/__init__.py:1644
callback
static void callback(void *arg, int status, int timeouts, struct hostent *host)
Definition: acountry.c:224
async_customized_auth_client.AuthGateway
Definition: async_customized_auth_client.py:33
main
Definition: main.py:1
grpc.ssl_channel_credentials
def ssl_channel_credentials(root_certificates=None, private_key=None, certificate_chain=None)
Definition: src/python/grpcio/grpc/__init__.py:1607
async_customized_auth_client.send_rpc
helloworld_pb2.HelloReply send_rpc(grpc.aio.Channel channel)
Definition: async_customized_auth_client.py:71
async_customized_auth_client.main
None main()
Definition: async_customized_auth_client.py:84
grpc.AuthMetadataPluginCallback
Definition: src/python/grpcio/grpc/__init__.py:604


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:58:35