Skip to content

Commit f319825

Browse files
committed
feat: add AuthInterceptor for gRPC authentication handling
1 parent 6617da0 commit f319825

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

main.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
import grpc
77

8+
from src.interceptor.auth_interceptor import AuthInterceptor
9+
810
current_dir = os.path.dirname(os.path.abspath(__file__))
911
venv_site_packages = os.path.join(current_dir, ".venv", "lib", "python3.12", "site-packages")
1012

@@ -25,7 +27,10 @@
2527

2628
if __name__ == '__main__':
2729

28-
server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=10))
30+
server = grpc.server(
31+
concurrent.futures.ThreadPoolExecutor(max_workers=10),
32+
interceptors=[AuthInterceptor()]
33+
)
2934
generate_pb2_grpc.add_GenerateServiceServicer_to_server(GenerateService(), server)
3035
info_pb2_grpc.add_InfoServiceServicer_to_server(InfoService(), server)
3136

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import os
2+
3+
import grpc
4+
import jwt
5+
6+
VALID_TOKEN = os.getenv('SECURITY_TOKEN', 'velorum-internal-communication-secret')
7+
8+
class AuthInterceptor(grpc.ServerInterceptor):
9+
10+
def intercept_service(self, continuation, handler_call_details):
11+
metadata = dict(handler_call_details.invocation_metadata or [])
12+
auth_token = metadata.get('authorization', '')
13+
14+
if not auth_token:
15+
return self._abort_handler()
16+
17+
try:
18+
jwt.decode(
19+
auth_token,
20+
VALID_TOKEN,
21+
algorithms=['HS256']
22+
)
23+
except Exception as e:
24+
print(e)
25+
return self._abort_handler()
26+
27+
return continuation(handler_call_details)
28+
29+
def _abort_handler(self, details="Invalid or missing authentication token"):
30+
def abort_handler(request, context):
31+
context.abort(
32+
code=grpc.StatusCode.UNAUTHENTICATED,
33+
details=details
34+
)
35+
36+
return grpc.unary_unary_rpc_method_handler(abort_handler)

0 commit comments

Comments
 (0)