async_customized_auth_server.py
Go to the documentation of this file.
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 """Server of the Python AsyncIO example of customizing authentication mechanism."""
15 
16 import argparse
17 import asyncio
18 import logging
19 from typing import Awaitable, Callable, Tuple
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: grpc.aio.ServicerContext) -> None:
39  context.abort(grpc.StatusCode.UNAUTHENTICATED, 'Invalid signature')
40 
42 
43  async def intercept_service(
44  self, continuation: Callable[[grpc.HandlerCallDetails],
45  Awaitable[grpc.RpcMethodHandler]],
46  handler_call_details: grpc.HandlerCallDetails
48  # Example HandlerCallDetails object:
49  # _HandlerCallDetails(
50  # method=u'/helloworld.Greeter/SayHello',
51  # invocation_metadata=...)
52  method_name = handler_call_details.method.split('/')[-1]
53  expected_metadata = (_SIGNATURE_HEADER_KEY, method_name[::-1])
54  if expected_metadata in handler_call_details.invocation_metadata:
55  return await continuation(handler_call_details)
56  else:
57  return self._abort_handler
58 
59 
61 
62  async def SayHello(self, request: helloworld_pb2.HelloRequest,
63  unused_context) -> helloworld_pb2.HelloReply:
64  return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
65 
66 
67 async def run_server(port: int) -> Tuple[grpc.aio.Server, int]:
68  # Bind interceptor to server
69  server = grpc.aio.server(interceptors=(SignatureValidationInterceptor(),))
71 
72  # Loading credentials
73  server_credentials = grpc.ssl_server_credentials(((
74  _credentials.SERVER_CERTIFICATE_KEY,
75  _credentials.SERVER_CERTIFICATE,
76  ),))
77 
78  # Pass down credentials
79  port = server.add_secure_port(_LISTEN_ADDRESS_TEMPLATE % port,
80  server_credentials)
81 
82  await server.start()
83  return server, port
84 
85 
86 async def main() -> None:
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  server, port = await run_server(args.port)
96  logging.info('Server is listening at port :%d', port)
97  await server.wait_for_termination()
98 
99 
100 if __name__ == '__main__':
101  logging.basicConfig(level=logging.INFO)
102  asyncio.run(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.aio._base_server.Server
Definition: _base_server.py:28
grpc.aio._interceptor.ServerInterceptor
Definition: aio/_interceptor.py:48
async_customized_auth_server.SimpleGreeter.SayHello
helloworld_pb2.HelloReply SayHello(self, helloworld_pb2.HelloRequest request, unused_context)
Definition: async_customized_auth_server.py:62
async_customized_auth_server.SignatureValidationInterceptor.__init__
def __init__(self)
Definition: async_customized_auth_server.py:36
async_customized_auth_server.SignatureValidationInterceptor._abort_handler
_abort_handler
Definition: async_customized_auth_server.py:41
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
async_customized_auth_server.SignatureValidationInterceptor.intercept_service
grpc.RpcMethodHandler intercept_service(self, Callable[[grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler]] continuation, grpc.HandlerCallDetails handler_call_details)
Definition: async_customized_auth_server.py:43
async_customized_auth_server.SimpleGreeter
Definition: async_customized_auth_server.py:60
helloworld_pb2.HelloReply
HelloReply
Definition: helloworld/helloworld_pb2.py:100
async_customized_auth_server.run_server
Tuple[grpc.aio.Server, int] run_server(int port)
Definition: async_customized_auth_server.py:67
async_customized_auth_server.SignatureValidationInterceptor
Definition: async_customized_auth_server.py:34
async_customized_auth_server.main
None main()
Definition: async_customized_auth_server.py:86
helloworld_pb2_grpc.GreeterServicer
Definition: helloworld/helloworld_pb2_grpc.py:24
main
Definition: main.py:1
grpc.HandlerCallDetails
Definition: src/python/grpcio/grpc/__init__.py:1324
helloworld_pb2_grpc.add_GreeterServicer_to_server
def add_GreeterServicer_to_server(servicer, server)
Definition: helloworld/helloworld_pb2_grpc.py:36
grpc.RpcMethodHandler
Definition: src/python/grpcio/grpc/__init__.py:1288


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