customized_auth_server.py
Go to the documentation of this file.
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 
35 
36  def __init__(self):
37 
38  def abort(ignored_request, context):
39  context.abort(grpc.StatusCode.UNAUTHENTICATED, 'Invalid signature')
40 
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 
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(),))
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()
grpc.unary_unary_rpc_method_handler
def unary_unary_rpc_method_handler(behavior, request_deserializer=None, response_serializer=None)
Definition: src/python/grpcio/grpc/__init__.py:1510
grpc.ServerInterceptor
Definition: src/python/grpcio/grpc/__init__.py:1373
customized_auth_server.SignatureValidationInterceptor._abortion
_abortion
Definition: customized_auth_server.py:41
customized_auth_server.main
def main()
Definition: customized_auth_server.py:86
customized_auth_server.SignatureValidationInterceptor.__init__
def __init__(self)
Definition: customized_auth_server.py:36
grpc.ssl_server_credentials
def ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False)
Definition: src/python/grpcio/grpc/__init__.py:1709
helloworld_pb2.HelloReply
HelloReply
Definition: helloworld/helloworld_pb2.py:100
customized_auth_server.SignatureValidationInterceptor
Definition: customized_auth_server.py:34
grpc.server
def server(thread_pool, handlers=None, interceptors=None, options=None, maximum_concurrent_rpcs=None, compression=None, xds=False)
Definition: src/python/grpcio/grpc/__init__.py:2034
customized_auth_server.SimpleGreeter
Definition: customized_auth_server.py:56
helloworld_pb2_grpc.GreeterServicer
Definition: helloworld/helloworld_pb2_grpc.py:24
main
Definition: main.py:1
customized_auth_server.SimpleGreeter.SayHello
def SayHello(self, request, unused_context)
Definition: customized_auth_server.py:58
customized_auth_server.run_server
def run_server(port)
Definition: customized_auth_server.py:63
helloworld_pb2_grpc.add_GreeterServicer_to_server
def add_GreeterServicer_to_server(servicer, server)
Definition: helloworld/helloworld_pb2_grpc.py:36
customized_auth_server.SignatureValidationInterceptor.intercept_service
def intercept_service(self, continuation, handler_call_details)
Definition: customized_auth_server.py:43


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