-
Notifications
You must be signed in to change notification settings - Fork 26
Interception of HTTP requests in ksqlDB.RestApi.Client DotNet Authentication
Tomas Fabian edited this page May 21, 2022
·
7 revisions
You can use the built in SetBasicAuthCredentials for Basic http authentication (v2.0.0):
string userName = "fred";
string password = "letmein";
var options = new KSqlDbContextOptionsBuilder().UseKSqlDb(@"http:\\localhost:8088")
.SetBasicAuthCredentials(userName, password)
.Options;
await using var context = new KSqlDBContext(options);
In order to provide other means for http authentications, override DelegatingHandler.SendAsync in the following way and add it to the http client's constructor:
internal class BearerAuthHandler : DelegatingHandler
{
public BearerAuthHandler()
{
InnerHandler = new HttpClientHandler();
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var token = "xoidiag"; //CreateToken();
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
return base.SendAsync(request, cancellationToken);
}
}
internal class HttpClientFactoryWithBearerAuth : IHttpClientFactory
{
private readonly Uri uri;
public HttpClientFactoryWithBearerAuth(Uri uri)
{
this.uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
public HttpClient CreateClient()
{
return new HttpClient(new BearerAuthHandler())
{
BaseAddress = uri
};
}
}
Override the registration of IHttpClientFactory:
public class KSqlDBContextWithAuth : KSqlDBContext
{
private readonly KSqlDBContextOptions contextOptions;
public KSqlDBContextWithAuth(KSqlDBContextOptions contextOptions)
: base(contextOptions)
{
this.contextOptions = contextOptions ?? throw new ArgumentNullException(nameof(contextOptions));
}
protected override void OnConfigureServices(IServiceCollection serviceCollection, KSqlDBContextOptions contextOptions)
{
serviceCollection.AddSingleton<IHttpClientFactory, HttpClientFactoryWithBearerAuth>(sp => new HttpClientFactoryWithBearerAuth(new Uri(contextOptions.Url)));
base.OnConfigureServices(serviceCollection, contextOptions);
}
}