Debian Codegraph @

examples/python/auth/customized_auth_client.py

raw
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
16 import argparse
17 import contextlib
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
33 class AuthGateway(grpc.AuthMetadataPlugin):
34
35 def __call__(self, context, callback):
36 """Implements authentication by passing metadata to a callback.
37
38 Implementations of this method must not block.
39
40 Args:
41 context: An AuthMetadataContext providing information on the RPC that
42 the plugin is being called to authenticate.
43 callback: An AuthMetadataPluginCallback to be invoked either
44 synchronously or asynchronously.
45 """
46 # Example AuthMetadataContext object:
47 # AuthMetadataContext(
48 # service_url=u'https://localhost:50051/helloworld.Greeter',
49 # method_name=u'SayHello')
50 signature = context.method_name[::-1]
51 callback(((_SIGNATURE_HEADER_KEY, signature),), None)
52
53
54 @contextlib.contextmanager
55 def create_client_channel(addr):
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.secure_channel(addr, composite_credentials)
68 yield channel
69
70
71 def send_rpc(channel):
72 stub = helloworld_pb2_grpc.GreeterStub(channel)
73 request = helloworld_pb2.HelloRequest(name='you')
74 try:
75 response = 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 def main():
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 with create_client_channel(_SERVER_ADDR_TEMPLATE % args.port) as channel:
94 send_rpc(channel)
95
96
97 if __name__ == '__main__':
98 logging.basicConfig(level=logging.INFO)
99 main()