c# - C# - etcd GRPC 客户端基本身份验证
问题描述
我正在尝试为 etcd v3+ 实现 C# GRPC 客户端。我能够通过无身份验证和通道 ssl 身份验证进行连接。但是,我也在尝试找出基本的身份验证机制。这是我到目前为止的实现。
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 文档
更新: 如果有人想查看完整的源代码,这里是项目的链接。
解决方案
我通过参考此处的 REST api 文档解决了这个问题。
添加私有属性。
Metadata headers;
更新Autheticate()
以添加身份验证标头。
headers = new Metadata();
headers.Add("Authorization", authToken);
更新Get()
以传递标题。
var rangeResponse = kvClient.Range(rangeRequest, headers);
推荐阅读
- python - 我应该怎么处理这个错误?/ 不支持的操作数类型:“str”和“str”
- javascript - Vue JSON 读写
- python - 为什么要多次插入元素?
- java - 如何加载保存到我的标记 ID 的图像并显示在该特定标记的自定义信息窗口中?
- scrapy - 如何从:使用带有 css 选择器的 Scrapy 获取 Href
- json - Json 身份验证请求正文包含美元符号
- javascript - “Javascript - 权威指南” - 未捕获的 TypeError:trace(...) 不是函数
- networking - 当系统没有连接任何东西时,单个 DNS 查询会发生什么?
- angular - 角材料
默认值选择来自 - java - JPA 规范
加入查询