我按照从 here 生成 Python gPRC 客户端的说明进行操作但难以为请求提供 token
不安全的 channel 不起作用
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)
A CallCredentials has to be used with secure Channel, otherwise the metadata will not be transmitted to the server.
但是,我该如何创建安全通道,因为创建这些 ChannelCredentials 的方法对应于 ssl 或类似的方法,不是吗?
除此之外,似乎可以简单地解析元组 {'Authorization':'Bearer <TOKEN>'}
作为 here 之类的元数据.但是,我注意到 - 正如评论中提到的那样 - 不允许使用大写字符。
带凭据的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)
总结:如何使用访问 token 对我的客户端进行身份验证?
最佳答案
如同docstring所述:
A CallCredentials may be composed with ChannelCredentials to always assert identity for every call over that Channel.
ChannelCredentials
对象是您从 grpc.secure_channel
中发出的类型错误所尖叫的。
要进行该组合,您需要使用 SSL/TLS 加密 channel 。
这是一个带有 token 的客户端示例:
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.com/joekottke/python-grpc-ssl或者这个 https://www.sandtable.com/using-ssl-with-grpc-in-python/ . official doc看看也可能会有所帮助。
token 是您不希望任何人嗅探的东西,我想这就是为什么 gRPC 库要求您在 secure_channel
中使用它。
关于仅使用不记名 token 的 Python gRPC 客户端请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727828/