Add `authorization: Bearer ` to every outgoing RPC. Implemented as an interceptor (not call credentials) so it works on both plaintext and TLS channels without needing `grpc.composite_channel_credentials`. The token provider is invoked per call, so callers can swap tokens at
| 66 | |
| 67 | |
| 68 | class _BearerAuthInterceptor( |
| 69 | grpc.UnaryUnaryClientInterceptor, |
| 70 | grpc.UnaryStreamClientInterceptor, |
| 71 | grpc.StreamUnaryClientInterceptor, |
| 72 | grpc.StreamStreamClientInterceptor, |
| 73 | ): |
| 74 | """Add `authorization: Bearer <token>` to every outgoing RPC. |
| 75 | |
| 76 | Implemented as an interceptor (not call credentials) so it works on |
| 77 | both plaintext and TLS channels without needing |
| 78 | `grpc.composite_channel_credentials`. The token provider is invoked |
| 79 | per call, so callers can swap tokens at runtime by mutating shared |
| 80 | state or returning a fresh value from the callable. |
| 81 | """ |
| 82 | |
| 83 | def __init__(self, token_provider: Callable[[], str]) -> None: |
| 84 | self._token_provider = token_provider |
| 85 | |
| 86 | def _attach(self, details: grpc.ClientCallDetails) -> grpc.ClientCallDetails: |
| 87 | original_metadata = getattr(details, "metadata", None) |
| 88 | metadata = list(original_metadata) if original_metadata else [] |
| 89 | metadata.append(("authorization", f"Bearer {self._token_provider()}")) |
| 90 | return _ClientCallDetails( |
| 91 | getattr(details, "method", None), |
| 92 | getattr(details, "timeout", None), |
| 93 | metadata, |
| 94 | getattr(details, "credentials", None), |
| 95 | getattr(details, "wait_for_ready", None), |
| 96 | getattr(details, "compression", None), |
| 97 | ) |
| 98 | |
| 99 | def intercept_unary_unary(self, continuation, client_call_details, request): |
| 100 | return continuation(self._attach(client_call_details), request) |
| 101 | |
| 102 | def intercept_unary_stream(self, continuation, client_call_details, request): |
| 103 | return continuation(self._attach(client_call_details), request) |
| 104 | |
| 105 | def intercept_stream_unary( |
| 106 | self, continuation, client_call_details, request_iterator |
| 107 | ): |
| 108 | return continuation(self._attach(client_call_details), request_iterator) |
| 109 | |
| 110 | def intercept_stream_stream( |
| 111 | self, continuation, client_call_details, request_iterator |
| 112 | ): |
| 113 | return continuation(self._attach(client_call_details), request_iterator) |
| 114 | |
| 115 | |
| 116 | def _normalize_bearer( |
no outgoing calls