customized_auth_client.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # Copyright 2019 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 example of customizing authentication mechanism."""
  15. import argparse
  16. import contextlib
  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, callback):
  28. """Implements authentication by passing metadata to a callback.
  29. Implementations of this method must not block.
  30. Args:
  31. context: An AuthMetadataContext providing information on the RPC that
  32. the plugin is being called to authenticate.
  33. callback: An AuthMetadataPluginCallback to be invoked either
  34. synchronously or asynchronously.
  35. """
  36. # Example AuthMetadataContext object:
  37. # AuthMetadataContext(
  38. # service_url=u'https://localhost:50051/helloworld.Greeter',
  39. # method_name=u'SayHello')
  40. signature = context.method_name[::-1]
  41. callback(((_SIGNATURE_HEADER_KEY, signature),), None)
  42. @contextlib.contextmanager
  43. def create_client_channel(addr):
  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.secure_channel(addr, composite_credentials)
  56. yield channel
  57. def send_rpc(channel):
  58. stub = helloworld_pb2_grpc.GreeterStub(channel)
  59. request = helloworld_pb2.HelloRequest(name='you')
  60. try:
  61. response = 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. def main():
  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. with create_client_channel(_SERVER_ADDR_TEMPLATE % args.port) as channel:
  77. send_rpc(channel)
  78. if __name__ == '__main__':
  79. logging.basicConfig(level=logging.INFO)
  80. main()