I am trying to implement a C# GRPC client for etcd v3+.I am able to connect via no auth and channel ssl auth.However, I am trying to figure out basic authentication mechanism as well.Here's my implementation till now.
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;
}
}
}
Using the authenticate() method I am able to get the token from etcd server but unable to find a way to use the same in subsequent calls (Get, Put etc.).
Protobuf doc used for generating client code can be found here
Update: In case anyone wanna have a look at the full source code , here's the link to project.
I solved it by referring to REST api docs here.
Add a private property.
Metadata headers;
Updated Autheticate()
to add auth header.
headers = new Metadata();
headers.Add("Authorization", authToken);
Updated Get()
to pass header.
var rangeResponse = kvClient.Range(rangeRequest, headers);