[英]Python gRPC client request only with bearer token
我按照從此處生成 Python gPRC 客戶端的說明操作,但很難為請求提供令牌
不安全通道不起作用
auth_creds = grpc.access_token_call_credentials(TOKEN)
channel = grpc.insecure_channel('localhost:10000', auth_creds)
>> TypeError: 'CallCredentials' object is not iterable
安全通道也不起作用
auth_creds = grpc.access_token_call_credentials(TOKEN)
channel = grpc.secure_channel('localhost:10000', auth_creds)
>> TypeError: Argument 'channel_credentials' has incorrect type (expected grpc._cython.cygrpc.ChannelCredentials, got grpc._cython.cygrpc.MetadataPluginCallCredentials)
CallCredentials 必須與安全通道一起使用,否則元數據將不會傳輸到服務器。
但是,我如何創建一個安全通道,因為創建這些 ChannelCredentials 的方法對應於 ssl 或類似的,不是嗎?
除此之外,似乎可以像這里一樣簡單地將元組{'Authorization':'Bearer <TOKEN>'}
解析為元數據。 但是,我注意到 - 正如在提出的評論中一樣 - 不允許使用大寫字符。
with_call 帶有憑據的方法也不起作用
auth_creds = grpc.access_token_call_credentials(TOKEN)
channel = grpc.secure_channel('localhost:10000', auth_creds)
stub = foo_bar_pb2_grpc.ServiceStub(channel)
response = stub.Get.with_call(message_pb2.Message(), credentials=auth_creds)
>> TypeError: Argument 'channel_credentials' has incorrect type (expected grpc._cython.cygrpc.ChannelCredentials, got grpc._cython.cygrpc.MetadataPluginCallCredentials)
with_call 帶有元數據的方法也不起作用
metadata = 'Authorization', 'Bearer <TOKEN>'
channel = grpc.insecure_channel('localhost:10000')
stub = foo_bar_pb2_grpc.ServiceStub(channel)
response = stub.Get.with_call(message_pb2.Message(), metadata=metadata))
>> ValueError: too many values to unpack (expected 2)
總結:如何使用訪問令牌驗證我的客戶端?
如同一文檔字符串所述:
CallCredentials 可以與 ChannelCredentials 組成,以始終為通過該 Channel 的每個調用聲明身份。
和ChannelCredentials
object 是您來自grpc.secure_channel
的類型錯誤所尖叫的。 要進行該組合,您需要使用 SSL/TLS 加密通道。 這是一個帶有令牌的客戶端示例:
with open("server.crt", 'rb') as fd:
root_c = fd.read()
scc = grpc.ssl_channel_credentials(root_certificates=root_c)
tok = grpc.access_token_call_credentials("super-secret-token")
ccc = grpc.composite_channel_credentials(scc, tok)
with grpc.secure_channel("localhost:8080", ccc) as channel:
#... create stub and do the call
pass
For some more complete examples with SSL checkout this https://github.com/joekottke/python-grpc-ssl or this https://www.sandtable.com/using-ssl-with-grpc-in-python/ . 官方文檔也可能有助於查看。
令牌是您不希望任何人嗅到的東西,我想這就是為什么您需要在 gRPC 庫的secure_channel
中使用它的原因。
我在嘗試在安全通道中發送自定義 header 時遇到了類似的問題。
就我而言,問題來自使用:
metadata = (('my-header-key', 'my-header-value'))
代替:
metadata = [('my-header-key', 'my-header-value')]
我的代碼:
credentials = grpc.ssl_channel_credentials()
with grpc.secure_channel("<HOST>:<PORT>", credentials) as channel:
rpc_service = my_pb2_grpc.MyServiceStub(channel)
request = my_pb2.MyData(my_data='data')
metadata = [('my-header-key', 'my-header-value')]
response = rpc_service.MyMethod(request=request, metadata=metadata)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.