我按照说明从以下地方生成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)
总结了一下。如何用访问令牌验证客户端?
如同上面所说 docstring:
一个CallCredentials可以和ChannelCredentials组成,始终为该Channel上的每一次呼叫申明身份。
和一个 ChannelCredentials
对象是你的类型错误从 grpc.secure_channel
要做到这一点,你需要用SSLTLS来加密通道,这是一个带有令牌的客户端例子。
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
更多关于SSL的完整例子请看这里 https:/github.comjoekottkepython-grpc-ssl。 或者这个 https:/www.sandtable.comusing-ssl-with-grpc-in-python. 该 正式文件 可能也会对你有所帮助。
令牌是你不想让任何人闻到的东西,我想这也是为什么要求你必须在 secure_channel
由gRPC库。