ARTICLE AD BOX
In my opinion, let security experts disagree all they want here:
You build a DI setup, Singleton, that loads the API-key in from Something like Azure vault, or similar.
Then you create an instance to provide for the program, such that if you need the mcpclient instance, you simply DI it in, either as a parameter inject, or constructor inject.
F.x I did this with an Httpcient: (In programs.cs)
builder.Services.AddHttpClient<CustomHttpClient>(client => { client.BaseAddress = new Uri("https://baseUrl.azurewebsites.net/"); }) .AddHttpMessageHandler<CustomHttpClientAuthHandler>();Then in an AuthClass:
public class CustomHttpClientAuthHandler : DelegatingHandler { private readonly ITokenProvider _tokenProvider; private string _clientSecret = string.Empty; public TalmundoAuthHandler(ITokenProvider tokenProvider, IConfiguration configuration) { _tokenProvider = tokenProvider; _clientSecret = configuration["API-KEY"] ?? string.Empty; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var token = await _tokenProvider.GetAccessTokenAsync(); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Headers.Add("Ocp-Apim-Subscription-Key", _clientSecret); return await base.SendAsync(request, cancellationToken); } }This makes it easy to test, easy to change method of obtaining a token.
It is clear how and when it happens.
So everytime this
CustomHttpClientAuthHandlerhas its method
SendAsync()Called, it will ask for a token, into the header, and then provide a subscription key after, with a configuration provided clientsecret, done at the time of constructor is called.
You don't have to do a constructor injection, you can do whatever.
But all authentication is handled here in this code, prior to all requests sent, via the CustomHttpClient.
Now an mcpClient, acts as a HttpClient, so it should be allowed to do this, but full disclaimer, I have never tried that, so I am not 100% sure this will work, I would try it? Let me know if it does.
