async_customized_auth_client.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. import argparse
  16. import asyncio
  17. import logging
  18. import _credentials
  19. import grpc
  20. helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
  21. "helloworld.proto")
  22. _LOGGER = logging.getLogger(__name__)
  23. _LOGGER.setLevel(logging.INFO)
  24. _SERVER_ADDR_TEMPLATE = 'localhost:%d'
  25. _SIGNATURE_HEADER_KEY = 'x-signature'
  26. class AuthGateway(grpc.AuthMetadataPlugin):
  27. def __call__(self, context: grpc.AuthMetadataContext,
  28. callback: grpc.AuthMetadataPluginCallback) -> None:
  29. """Implements authentication by passing metadata to a callback.
  30. Implementations of this method must not block.
  31. Args:
  32. context: An AuthMetadataContext providing information on the RPC that
  33. the plugin is being called to authenticate.
  34. callback: An AuthMetadataPluginCallback to be invoked either
  35. synchronously or asynchronously.
  36. """
  37. # Example AuthMetadataContext object:
  38. # AuthMetadataContext(
  39. # service_url=u'https://localhost:50051/helloworld.Greeter',
  40. # method_name=u'SayHello')
  41. signature = context.method_name[::-1]
  42. callback(((_SIGNATURE_HEADER_KEY, signature),), None)
  43. def create_client_channel(addr: str) -> grpc.aio.Channel:
  44. # Call credential object will be invoked for every single RPC
  45. call_credentials = grpc.metadata_call_credentials(AuthGateway(),
  46. name='auth gateway')
  47. # Channel credential will be valid for the entire channel
  48. channel_credential = grpc.ssl_channel_credentials(
  49. _credentials.ROOT_CERTIFICATE)
  50. # Combining channel credentials and call credentials together
  51. composite_credentials = grpc.composite_channel_credentials(
  52. channel_credential,
  53. call_credentials,
  54. )
  55. channel = grpc.aio.secure_channel(addr, composite_credentials)
  56. return channel
  57. async def send_rpc(channel: grpc.aio.Channel) -> helloworld_pb2.HelloReply:
  58. stub = helloworld_pb2_grpc.GreeterStub(channel)
  59. request = helloworld_pb2.HelloRequest(name='you')
  60. try:
  61. response = await stub.SayHello(request)
  62. except grpc.RpcError as rpc_error:
  63. _LOGGER.error('Received error: %s', rpc_error)
  64. return rpc_error
  65. else:
  66. _LOGGER.info('Received message: %s', response)
  67. return response
  68. async def main() -> None:
  69. parser = argparse.ArgumentParser()
  70. parser.add_argument('--port',
  71. nargs='?',
  72. type=int,
  73. default=50051,
  74. help='the address of server')
  75. args = parser.parse_args()
  76. channel = create_client_channel(_SERVER_ADDR_TEMPLATE % args.port)
  77. await send_rpc(channel)
  78. await channel.close()
  79. if __name__ == '__main__':
  80. logging.basicConfig(level=logging.INFO)
  81. asyncio.run(main())