Debian Codegraph @

examples/python/auth/customized_auth_server.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 """Server of the Python example of customizing authentication mechanism."""
15
16 import argparse
17 from concurrent import futures
18 import contextlib
19 import logging
20
21 import _credentials
22 import grpc
23
24 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
25 "helloworld.proto")
26
27 _LOGGER = logging.getLogger(__name__)
28 _LOGGER.setLevel(logging.INFO)
29
30 _LISTEN_ADDRESS_TEMPLATE = 'localhost:%d'
31 _SIGNATURE_HEADER_KEY = 'x-signature'
32
33
34 class SignatureValidationInterceptor(grpc.ServerInterceptor):
35
36 def __init__(self):
37
38 def abort(ignored_request, context):
39 context.abort(grpc.StatusCode.UNAUTHENTICATED, 'Invalid signature')
40
41 self._abortion = grpc.unary_unary_rpc_method_handler(abort)
42
43 def intercept_service(self, continuation, handler_call_details):
44 # Example HandlerCallDetails object:
45 # _HandlerCallDetails(
46 # method=u'/helloworld.Greeter/SayHello',
47 # invocation_metadata=...)
48 method_name = handler_call_details.method.split('/')[-1]
49 expected_metadata = (_SIGNATURE_HEADER_KEY, method_name[::-1])
50 if expected_metadata in handler_call_details.invocation_metadata:
51 return continuation(handler_call_details)
52 else:
53 return self._abortion
54
55
56 class SimpleGreeter(helloworld_pb2_grpc.GreeterServicer):
57
58 def SayHello(self, request, unused_context):
59 return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
60
61
62 @contextlib.contextmanager
63 def run_server(port):
64 # Bind interceptor to server
65 server = grpc.server(futures.ThreadPoolExecutor(),
66 interceptors=(SignatureValidationInterceptor(),))
67 helloworld_pb2_grpc.add_GreeterServicer_to_server(SimpleGreeter(), server)
68
69 # Loading credentials
70 server_credentials = grpc.ssl_server_credentials(((
71 _credentials.SERVER_CERTIFICATE_KEY,
72 _credentials.SERVER_CERTIFICATE,
73 ),))
74
75 # Pass down credentials
76 port = server.add_secure_port(_LISTEN_ADDRESS_TEMPLATE % port,
77 server_credentials)
78
79 server.start()
80 try:
81 yield server, port
82 finally:
83 server.stop(0)
84
85
86 def main():
87 parser = argparse.ArgumentParser()
88 parser.add_argument('--port',
89 nargs='?',
90 type=int,
91 default=50051,
92 help='the listening port')
93 args = parser.parse_args()
94
95 with run_server(args.port) as (server, port):
96 logging.info('Server is listening at port :%d', port)
97 server.wait_for_termination()
98
99
100 if __name__ == '__main__':
101 logging.basicConfig(level=logging.INFO)
102 main()