gpt4 book ai didi

c# - 如何从 SslCredentials 和 token 字符串创建 CallCredentials

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:17 30 4
gpt4 key购买 nike

我正在将 gRPC 客户端从 python 移植到 c#。 python 客户端和 c# 客户端都使用来自 grpc.io 的 gRPC 框架。

Python 客户端使用以下代码打开一个安全的、未经身份验证的 channel ,然后使用该 channel 获取 token 字符串,然后使用该字符串通过 grpc.composite_channel_credentials() 函数创建调用凭证:

channel = grpc.secure_channel(url_server_address, ssl_creds)
stub = gateway.GatewayStub(channel)

# Acquire access token via password authentication
pw_cmd = gateway.PasswordAuthenticateCmd(account_name=url.username, password=url.password)
auth_rsp = stub.PasswordAuthenticate(pw_cmd)

# Open a secure, authenticated channel
auth_creds = grpc.access_token_call_credentials(auth_rsp.access_token)
composite_creds = grpc.composite_channel_credentials(ssl_creds, auth_creds)
channel = grpc.secure_channel(url_server_address, composite_creds)
stub = gateway.GatewayStub(channel)

在 c# 中,我已经能够编译 Protocol Buffer 定义,并连接生成的客户端以成功获取访问 token :

SslCredentials secureChannel = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel channel = new Channel(ServerURL, PortNum, secureChannel);

var client = new GrpcClient(new Grpc.Gateway.GatewayClient(channel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });

Console.WriteLine(response.AccessToken);

但是,从这里,我找不到类似于 grpc.composite_channel_credentials() 函数的 c# 函数来获取 SslCredentials 和访问 token 字符串来创建组合凭证。

此处没有示例 https://grpc.io/docs/guides/auth.html这里使用一个标记字符串,我还没有找到任何其他示例。

最佳答案

我使用 CallCredentials.FromInterceptor() 解决了我的问题。

grpc.access_token_call_credentials() python 调用向元数据添加授权条目,并将其值设置为“Bearer”+ AccessToken,所以我只需要执行相同的操作:

SslCredentials secureCredentials = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel secureChannel = new Channel(ServerURL, PortNum, secureCredentials);

var client = new GrpcClient(new Grpc.Gateway.GatewayClient(secureChannel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });

var accessTokenCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
{
metadata.Add("authorization", "Bearer " + passwordResponse.AccessToken);
return TaskUtils.CompletedTask;
}));

var authenticatedCredentials = ChannelCredentials.Create(secureCredentials, accessTokenCredentials);
Channel authenticatedChannel = new Channel(hostURL, hostPort, authenticatedCredentials);

作为Jan在他的回答中指出,Grpc.Auth 命名空间中有一个函数与我编写的函数做同样的事情:https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58

关于c# - 如何从 SslCredentials 和 token 字符串创建 CallCredentials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54960613/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com