我正在尝试实现一个C# GRPC客户端,因为etcd v3+.I可以通过不通过auth和通道ssl auth.However进行连接,我也在尝试找出基本的身份验证机制,下面是我的实现。
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Grpc.Core;
using Etcdserverpb;
using Google.Protobuf;
using System.Runtime.CompilerServices;
using Grpc.Auth;
using Grpc.Core.Interceptors;
namespace myproj.etcd
{
public class EtcdClient
{
Channel channel;
KV.KVClient kvClient;
string host;
string username;
string password;
string authToken;
Auth.AuthClient authClient;
public EtcdClient(string host, string username, string password)
{
this.username = username;
this.password = password;
this.host = host;
Authenticate();
// Expirementing with the token, trying to achieve my goal.
channel = new Channel(host, ChannelCredentials.Create(ChannelCredentials.Insecure,
GoogleGrpcCredentials.FromAccessToken(this.authToken)));
// This works.
//channel = new Channel(host, ChannelCredentials.Insecure);
kvClient = new KV.KVClient(channel);
}
void Authenticate()
{
authClient = new Auth.AuthClient(new Channel(host,ChannelCredentials.Insecure));
var authRes = authClient.Authenticate(new AuthenticateRequest
{
Name = username,
Password = password
});
this.authToken = authRes.Token;
}
public string Get(string key)
{
try
{
var rangeRequest = new RangeRequest { Key = ByteString.CopyFromUtf8(key) };
var rangeResponse = kvClient.Range(rangeRequest);
if (rangeResponse.Count != 0)
{
return rangeResponse.Kvs[0].Value.ToStringUtf8().Trim();
}
}
catch (Exception ex)
{
}
return String.Empty;
}
}
}使用authenticate()方法,我可以从etcd服务器获得令牌,但无法找到在后续调用(Get、Put等)中使用令牌的方法。
用于生成客户端代码的Protobuf可以找到这里。
更新:,如果有人想看完整的源代码,下面是链接到项目。
发布于 2018-05-29 09:48:39
我通过引用REST文档这里来解决这个问题。
添加私有财产。
Metadata headers;更新Autheticate()以添加auth标头。
headers = new Metadata();
headers.Add("Authorization", authToken);更新Get()以传递标头。
var rangeResponse = kvClient.Range(rangeRequest, headers);https://stackoverflow.com/questions/50572412
复制相似问题