我正在将gRPC客户端从python移植到c#。 python客户端和c#客户端都使用来自grpc.io的gRPC框架。
python客户端使用以下代码打开安全的,未经身份验证的通道,然后将其用于采购令牌字符串,然后使用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#中,我已经能够编译协议缓冲区定义,并与生成的客户端连接以成功获取访问令牌:
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和访问令牌字符串来创建组合的凭据。
https://grpc.io/docs/guides/auth.html此处的示例均未使用标记字符串,但我在那里找不到其他示例。
答案 0 :(得分:1)
您要寻找的是: https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/CallCredentials.cs#L49和https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/ChannelCredentials.cs#L67。
答案 1 :(得分:0)
我使用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